<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      http://www.dbshop.net/
 * @copyright Copyright (c) 2012-2017 DBShop.net Inc. (http://www.dbshop.net)
 * @license   http://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风
 *
 */

namespace Dbapi\Controller;

use Dbapi\Config\apiConfig;
use Dbapi\Model\DbJsonModel;
use Zend\Config\Reader\Ini;
use Goods\Service\CouponRuleService;
use Zend\Filter\HtmlEntities;
use Zend\Validator\EmailAddress;

class JsonapiController extends JsonbaseController
{
    private $dbTables = array();
    private $translator;

    /**
     * 详单于测试接口是否成功
     * @return JsonModel
     */
    public function indexAction()
    {
        return $this->createJson('success', $this->getDbshopLang()->translate('接口连接成功！'));
    }
    /*============================================公共调用============================================*/
    /**
     * 获取商城基本信息
     * @return JsonModel
     */
    public function shopinfoAction()
    {
        $iniReader  = new Ini();
        $array      = $iniReader->fromFile(DBSHOP_PATH . '/data/moduledata/System/config.ini');
        $shopSystem = $array['shop_system'];

        $shopInfo   = array(
            'shop_name'         => $shopSystem['shop_name'],            //商城名称
            'shop_extend_name'  => $shopSystem['shop_extend_name'],     //商城扩展名称
            'shop_keywords'     => $shopSystem['shop_keywords'],        //商城关键字
            'shop_hot_keywords' => $shopSystem['shop_hot_keywords'],    //商城热门关键字
            'shop_description'  => $shopSystem['shop_description'],     //商城描述
            'shop_close'        => $shopSystem['shop_close'],           //商城状态，close 表示商城关闭
            'shop_close_info'   => $shopSystem['shop_close_info'],      //商城关闭后，显示的信息
            'shop_logo'         => $this->createDbshopImageUrl($shopSystem['shop_logo'], false),//商城Logo
        );

        return $this->createJsonData($shopInfo);
    }
    /**
     * 统计信息获取
     * post
     * user_token   必填，用户登录唯一标识
     * statis_type  选填，统计类型，如为空显示全部统计信息，coupon 优惠券（all 全部、0未启用、1启用、2已用、3过期）、favorites_num 商品收藏数、money 余额、integral_num 消费积分、integral_num_2 等级积分、not_evaluated_num未评价商品数、order 订单的相关数 数组形式显示（0已取消、10待付款、15付款中、20已付款、30待发货、40已发货、60订单完成、-40退货）
     * @return JsonModel
     */
    public function statisticsAction()
    {
        $userId     = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;  //用户id
        $statisType = isset($this->postData['statis_type']) ? trim($this->postData['statis_type']) : '';//统计类型

        $statisArray = array();

        if($userId > 0) {
            $favoritesNum = $this->getDbshopTable('UserFavoritesTable')->favoritesCountNum(array('user_id'=>$userId));
            $statisArray['favorites_num'] = $favoritesNum;

            $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$this->userData['user_id']));
            $statisArray['money']           = $userInfo->user_money;
            $statisArray['integral_num']    = $userInfo->user_integral_num;
            $statisArray['integral_num_2']  = $userInfo->integral_type_2_num;

            //未评价的商品（订单完成状态时的评价）
            $notEvaluatedNum = $this->getDbshopTable('OrderGoodsTable')->countOrderGoods(array('o.buyer_id'=>$userId, 'o.order_state>=60', 'dbshop_order_goods.comment_state=0'));
            $statisArray['not_evaluated_num'] = $notEvaluatedNum;

            $statisArray['order'] = $this->getDbshopTable('OrderTable')->allStateNumOrder(array('buyer_id'=>$userId));
            //优惠券
            $statisArray['coupon'] = $this->getDbshopTable('UserCouponTable')->allStateNumCoupon($userId);

            if(!empty($statisType) and isset($statisArray[$statisType])) {
                $array[$statisType] = $statisArray[$statisType];
                return $this->createJsonData(array($array));
            }
        }
        return $this->createJsonData($statisArray);
    }
    /*============================================公共调用============================================*/

    /*============================================广告相关============================================*/
    /**
     * 调用api内设置的广告
     * get
     * ad_code 调用标记
     * @return JsonModel
     */
    public function specialAdAction()
    {
        $adCode = isset($this->getData['ad_code']) ? trim($this->getData['ad_code']) : '';
        if(!empty($adCode)) {
            $adInfo = $this->getDbshopTable('ApiSetAdTable')->infoAd(array('dbapi_ad_code'=>$adCode));
            if($adInfo['dbapi_ad_type'] == 'image') $adInfo['dbapi_ad_body'] = $this->createDbshopImageUrl($adInfo['dbapi_ad_body']);
            if($adInfo['dbapi_ad_type'] == 'slide') {
                $slideArray = $this->getDbshopTable('ApiSetAdSlideTable')->listAdSlide(array('dbapi_ad_id'=>$adInfo['dbapi_ad_id']));
                if(is_array($slideArray) and !empty($slideArray)) {
                    foreach($slideArray as $key => $value) {
                        $value['dbapi_ad_slide_image'] = $this->createDbshopImageUrl($value['dbapi_ad_slide_image']);
                        $slideArray[$key] = $value;
                    }
                    $adInfo['dbapi_ad_body'] = $slideArray;
                }
            }
            return $this->createJsonData($adInfo);
        }
        return $this->createJsonData(array());
    }
    /*============================================广告相关============================================*/

    /*============================================cms相关============================================*/
    /**
     * 调用api内设置的文章
     * get
     * cms_code 调用标记
     * @return JsonModel
     */
    public function specialCmsAction()
    {
        $cmsCode = isset($this->getData['cms_code']) ? trim($this->getData['cms_code']) : '';
        if(!empty($cmsCode)) {
            $cmsList = $this->getDbshopTable('ApiSetCmsTable')->listApiCms(array('dbapi_cms_code'=>$cmsCode));
            if(is_array($cmsList) and !empty($cmsList)) {
                foreach($cmsList as $key => $value) {
                    $cmsValue = array(
                        'single_article_id'     => $value['single_article_id'],
                        'single_article_writer' => $value['single_article_writer'],
                        'single_article_title'  => $value['single_article_title'],
                        'single_article_body'   => $value['single_article_body']
                    );
                    $cmsList[$key] = $cmsValue;
                }
            }
            return $this->createJsonData($cmsList);
        }
        return $this->createJsonData(array());
    }

    /**
     * 获取单页cms信息
     * get
     * cms_id 必填，单页cms 的id
     * @return DbJsonModel
     */
    public function singleCmsAction()
    {
        $cmsId = isset($this->getData['cms_id']) ? intval($this->getData['cms_id']) : 0;
        if($cmsId > 0) {
            $cmsInfo = $this->getDbshopTable('SingleArticleTable')->infoSingleArticle(array('dbshop_single_article.single_article_id'=>$cmsId));
            if($cmsInfo) {
                $cmsInfo->single_article_body = $this->createDbshopGoodsBody($cmsInfo->single_article_body);
                $cmsInfo = (array) $cmsInfo;
                return $this->createJsonData($cmsInfo);
            }
        }
        return $this->createJsonData(array());
    }

    /**
     * 获取文章列表
     * get
     * class_id 必填，分类id，且不能为0
     * cms_num  可选，文章数，为空时默认为0，当不为空时，下面的两个参数无效
     * page     可选，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      可选，每页显示的商品数量，如果不填写默认是 10
     *
     * @return DbJsonModel
     */
    public function listCmsAction()
    {
        $classId    = isset($this->getData['class_id']) ? (int) $this->getData['class_id'] : 0;
        $cmsNum     = isset($this->getData['cms_num']) ? (int) $this->getData['cms_num'] : 0;

        $cmsList = array();
        if($classId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'] = 'dbshop_article.article_class_id='.$classId.' and dbshop_article.article_state=1';
            if($cmsNum > 0) {
                $cmsList = $this->getDbshopTable('ArticleTable')->apiArticleList($array, $cmsNum);
            } else {
                $cmsList = $this->getDbshopTable('ArticleTable')->apiArticleList($array);
            }
            if(is_array($cmsList) and !empty($cmsList)) {
                foreach($cmsList as $key => $value) {
                    $value['article_add_time_text'] = date("Y-m-d H:i", $value['article_add_time']);
                    $cmsList[$key] = $value;
                }
            }
        }
        return $this->createJsonData($cmsList);
    }

    /**
     * 文章内容
     * post
     * cms_id   必填，cms的id
     *
     * @return DbJsonModel
     */
    public function contentCmsAction()
    {
        $cmsId = isset($this->postData['cms_id']) ? (int) $this->postData['cms_id'] : 0;

        $cmsInfo = array();
        if($cmsId > 0) {
            $cmsInfo = $this->getDbshopTable('ArticleTable')->infoArticle(array('dbshop_article.article_id'=>$cmsId));
            if($cmsInfo) {
                $cmsInfo = (array) $cmsInfo;
                $cmsInfo['article_body'] = $this->createDbshopGoodsBody($cmsInfo['article_body']);
            }
        }
        return $this->createJsonData($cmsInfo);
    }
    /*============================================cms相关============================================*/

    /*============================================商品相关============================================*/
    /**
     * 调用api内设置的商品
     * get
     * goods_code 调用标记
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return DbJsonModel
     */
    public function specialGoodsAction()
    {
        $goodsCode = isset($this->getData['goods_code']) ? trim($this->getData['goods_code']) : '';
        if(!empty($goodsCode)) {
            $groupId = (isset($this->userData['group_id']) and $this->userData['group_id'] > 0) ? $this->userData['group_id'] : 0;
            $goodsList = $this->getDbshopTable('ApiGoodsTable')->goodsListPage(array('group_id'=>$groupId, 'limit'=>100, 'order'=>'goods_api.dbapi_goods_sort ASC','where'=>array('goods_api.dbapi_goods_code'=>$goodsCode), 'inner'=>array('dbshop_dbapi_goods'=>true)));
            if(is_array($goodsList) and !empty($goodsList)) {
                foreach($goodsList as $key => $value) {
                    $goodsValue = array(
                        'goods_id'                => $value['goods_id'],
                        'class_id'                => $value['one_class_id'],
                        'goods_item'              => $value['goods_item'],
                        'goods_price'             => $value['goods_price'],
                        'goods_shop_price'        => (isset($value['group_price']) and $value['group_price'] > 0) ? $value['group_price'] : $value['goods_shop_price'],
                        'goods_thumbnail_image'   => $this->createDbshopImageUrl($value['goods_thumbnail_image']),
                        'goods_name'              => $value['goods_name'],
                        'goods_extend_name'       => $value['goods_extend_name'],

                    );
                    $goodsValue['goods_price']      = $this->getServiceLocator()->get('frontHelper')->shopPrice($goodsValue['goods_price']);
                    $goodsValue['goods_shop_price'] = $this->getServiceLocator()->get('frontHelper')->shopPrice($goodsValue['goods_shop_price']);

                    $goodsList[$key] = $goodsValue;
                }
                return $this->createJsonData($goodsList);
            }
        }
        return $this->createJsonData(array());
    }
    /**
     * 获取商品分类
     * post
     * class_id 当class_id为空或者为0时，是获取全部商品分类；否则是获取指定分类下面的所有商品分类
     * @return JsonModel
     */
    public function goodsClassAction()
    {
        $classId    = isset($this->postData['class_id']) ? (int) $this->postData['class_id'] : 0;
        $classArray = $this->getDbshopTable('GoodsClassTable')->classOptions($classId, $this->getDbshopTable('GoodsClassTable')->listGoodsClass());

        //之所以做如下处理，是因为json会把php有key的数组原有排序重新作排序处理
        $array = array();
        if(!empty($classArray)) {
            foreach($classArray as $value) {
                if(!empty($value['class_icon'])) $value['class_icon']   = $this->createDbshopImageUrl($value['class_icon']);
                if(!empty($value['class_image'])) $value['class_image'] = $this->createDbshopImageUrl($value['class_image']);
                $array[] = $value;
            }
        }

        return $this->createJsonData($array);
    }
    /**
     * 获取商品顶级分类及二级分类
     * post
     * @return DbJsonModel
     */
    public function goodsTopAndSubClassAction()
    {
        $array['goods_class'] = array();
        $classArray = $this->getDbshopTable('GoodsClassTable')->listGoodsClass(array('dbshop_goods_class.class_top_id'=>0, 'dbshop_goods_class.class_state'=>1));
        if(!empty($classArray)) {
            foreach($classArray as $value) {
                if(!empty($value['class_icon'])) $value['class_icon']   = $this->createDbshopImageUrl($value['class_icon']);
                if(!empty($value['class_image'])) $value['class_image'] = $this->createDbshopImageUrl($value['class_image']);

                $subClassArray = $this->getDbshopTable('GoodsClassTable')->listGoodsClass(array('dbshop_goods_class.class_top_id'=>$value['class_id'], 'dbshop_goods_class.class_state'=>1));
                if(!empty($subClassArray)) {
                    foreach ($subClassArray as $subValue) {
                        $subValue['class_icon'] = $this->createDbshopImageUrl($subValue['class_icon']);
                        $subValue['class_image']= $this->createDbshopImageUrl($subValue['class_image']);

                        $value['sub_class'][] = $subValue;
                    }
                }
                $array['goods_class'][] = $value;
            }
        }
        return $this->createJsonData($array);
    }
    /**
     * 获取单一商品分类的信息
     * post
     * class_id 必填，且不能为0
     * @return JsonModel
     */
    public function oneGoodsClassAction()
    {
        $classId    = isset($this->postData['class_id']) ? (int) $this->postData['class_id'] : 0;
        $classInfo = array();
        if($classId != 0) {
            $array = $this->getDbshopTable('GoodsClassTable')->infoGoodsClass(array('class_id'=>$classId));
            if(!empty($array)) $classInfo = (array) $array;
            if(!empty($classInfo['class_icon'])) $classInfo['class_icon'] = $this->createDbshopImageUrl($classInfo['class_icon']);
            if(!empty($classInfo['class_image'])) $classInfo['class_image'] = $this->createDbshopImageUrl($classInfo['class_image']);
        }
        return $this->createJsonData($classInfo);
    }
    /**
     * 获取商品分类的标签信息
     * get
     * class_id 必填，且不能为0
     * tag_id_str 选填，当已经选择了tag_id时，再次打开时使用，多个tag_id请使用英文逗号分割
     * start_price  选填，检索价格区间，开始价格(已经填写时传递)
     * end_price    选填，检索价格区间，结束价格(已经填写时传递)
     * @return JsonModel
     */
    public function goodsClassTagAction()
    {
        $classId    = isset($this->getData['class_id']) ? (int) $this->getData['class_id'] : 0;
        $tagIdStr   = isset($this->getData['tag_id_str']) ? trim($this->getData['tag_id_str']) : '';
        $startPrice = isset($this->getData['start_price']) ? floatval($this->getData['start_price']) : 0;
        $endPrice   = isset($this->getData['end_price']) ? floatval($this->getData['end_price']) : 0;

        $array = array();
        if($classId > 0) {
            $array['class_tag_group'] = $this->getDbshopTable('GoodsClassShowTable')->arrayGoodsClassTagGroup(array('class_id'=>$classId));
            if(is_array($array['class_tag_group']) and !empty($array['class_tag_group'])) {
                $tagArray   = $this->getDbshopTable('GoodsTagTable')->listGoodsTag(array('dbshop_goods_tag.tag_group_id IN (' . implode(',', $array['class_tag_group']) . ')', 'e.language'=>$this->getDbshopLang()->getLocale()) , array('tag_group_sort ASC', 'dbshop_goods_tag.tag_sort ASC'));
                $array['goods_tag'] = array();
                $array['goods_tag_group'] = array();
                if(is_array($tagArray) and !empty($tagArray)) {
                    foreach ($tagArray as $tag_value) {
                        $array['goods_tag'][$tag_value['tag_group_id']][] = array('tag_id'=>$tag_value['tag_id'],'tag_name'=>$tag_value['tag_name']);
                        $array['goods_tag_group'][$tag_value['tag_group_id']] = $tag_value['tag_group_name'];
                    }
                }

                if(!empty($tagIdStr)) {
                    $array['selected_tag_id'] = explode(',', $tagIdStr);
                }

                if($startPrice > 0) $array['start_price'] = $startPrice;
                if($endPrice > 0) $array['end_price'] = $endPrice;
            }
        }
        return $this->createJsonData($array);
    }
    /**
     * 获取商品列表（商品分类）
     * get
     * class_id 必填，且不能为0
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * sort_type选填，默认是按照该分类的商品排序设置进行排序（time_asc、time_desc、click_asc、click_desc、price_asc、price_desc、sale_asc、sale_desc）
     * tag_id_str 选填，当选择了标签检索信息后，传过标签组合的字符串，多个标签id使用英文逗号分割
     * start_price  选填，检索价格区间，开始价格
     * end_price    选填，检索价格区间，结束价格
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return DbJsonModel
     */
    public function goodsListAction()
    {
        $classId    = isset($this->getData['class_id']) ? (int) $this->getData['class_id'] : 0;
        $sortType   = isset($this->getData['sort_type']) ? trim($this->getData['sort_type']) : '';
        $tagIdStr   = isset($this->getData['tag_id_str']) ? trim($this->getData['tag_id_str']) : '';
        $startPrice = isset($this->getData['start_price']) ? floatval($this->getData['start_price']) : 0;
        $endPrice   = isset($this->getData['end_price']) ? floatval($this->getData['end_price']) : 0;

        $goodsList  = array();
        if($classId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['order'] = 'goods_in.class_goods_sort ASC';
            $array['inner'] = array('goods_in_class'=>true);
            $array['where'] = 'goods_in.class_id='.$classId.' and dbshop_goods.goods_state=1';

            //排序
            if(!empty($sortType) and in_array($sortType, array('time_asc', 'time_desc', 'click_asc', 'click_desc', 'price_asc', 'price_desc', 'sale_asc', 'sale_desc'))) {
                $sortArray = array(
                    'time_asc'      => 'dbshop_goods.goods_add_time ASC',
                    'time_desc'     => 'dbshop_goods.goods_add_time DESC',
                    'click_asc'     => 'dbshop_goods.goods_click ASC',
                    'click_desc'    => 'dbshop_goods.goods_click DESC',
                    'price_asc'     => 'dbshop_goods.goods_shop_price+1 ASC',
                    'price_desc'    => 'dbshop_goods.goods_shop_price+1 DESC',
                    'sale_asc'      => 'buy_num ASC',
                    'sale_desc'     => 'buy_num DESC'
                );
                $array['order'] = $sortArray[$sortType];
            }
            //标签检索
            if(!empty($tagIdStr)) {
                $tagIdArray = explode(',', $tagIdStr);
                $sTagStr = '';
                foreach ($tagIdArray as $st_val) {
                    $st_val = (int) $st_val;//对组合后的tag_id进行重新整型处理，防止出现其他操作
                    $sTagStr .= 'dbshop_goods.goods_tag_str like \'%,' . $st_val .',%\' and ';
                }
                $sTagStr  = substr($sTagStr, 0, -5);
                $array['where'] .= ' and ' . $sTagStr;
            }

            //价格检索
            if($startPrice > 0) $array['where'] .= ' and dbshop_goods.goods_shop_price >= ' . $startPrice;
            if($endPrice > 0) $array['where'] .= ' and dbshop_goods.goods_shop_price <= ' . $endPrice;

            $array['group_id'] = (isset($this->userData['group_id']) and $this->userData['group_id'] > 0) ? $this->userData['group_id'] : 0;

            $goodsList = $this->getDbshopTable()->goodsListPage($array);

            if(is_array($goodsList) and !empty($goodsList)) {//进行图片地址转换，转换为公网可访问地址
                foreach($goodsList as $key => $value) {
                    $goodsList[$key]['goods_thumbnail_image'] = $this->createDbshopImageUrl($value['goods_thumbnail_image']);
                    $goodsList[$key]['goods_shop_price'] = (isset($value['group_price']) and $value['group_price'] > 0)
                        ? $this->getServiceLocator()->get('frontHelper')->shopPrice($value['group_price'])
                        : $this->getServiceLocator()->get('frontHelper')->shopPrice($value['goods_shop_price']);

                    unset($goodsList[$key]['goods_body']);
                }
            }

            return $this->createJsonData($goodsList);
        }
        return $this->createJsonData($goodsList, 'error');
    }
    /**
     * 获取对应商品的收藏信息
     * post
     * goods_id     必填，商品id
     * user_token   选填，用户登录唯一标识（当用户为登录状态时，需要传递该参数）
     * @return JsonModel
     */
    public function oneGoodsFavoriteInfoAction()
    {
        $goodsId    = isset($this->postData['goods_id']) ? (int) $this->postData['goods_id'] : 0;
        $userId     = isset($this->userData['user_id'])  ? $this->userData['user_id']  : 0;//用户id

        $array = array();
        if($goodsId > 0) {

            $favoritesNum = $this->getDbshopTable('UserFavoritesTable')->favoritesCountNum(array('goods_id'=>$goodsId));
            $array['goods_favorites_num'] = $favoritesNum;
            $array['user_favorites_state']= 0;
            if($userId > 0) {
                $favoritesInfo = $this->getDbshopTable('UserFavoritesTable')->infoFavorites(array('user_id'=>$userId, 'goods_id'=>$goodsId));
                if(!empty($favoritesInfo)) {
                    $array['user_favorites_state'] = 1;
                    $array['favorites_id'] = $favoritesInfo->favorites_id;
                }
            }
        }
        return $this->createJsonData($array);
    }

    /**
     * 获取商品信息
     * post
     * class_id 必填，商品分类id
     * goods_id 必填，商品id
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     *
     * @return DbJsonModel
     */
    public function goodsInfoAction()
    {
        $classId    = isset($this->postData['class_id']) ? (int) $this->postData['class_id'] : 0;
        $goodsId    = isset($this->postData['goods_id']) ? (int) $this->postData['goods_id'] : 0;
        $goodsInfo  = array();
        if($classId > 0 and $goodsId > 0) {
            $language = $this->getDbshopLang()->getLocale();

            $goodsInfo = $this->getDbshopTable('GoodsTable')->infoGoods(array('dbshop_goods.goods_id'=>$goodsId, 'e.language'=>$language));
            if($goodsInfo) {
                //判断优惠价格是否存在，是否过期
                $preferentialStart = (intval($goodsInfo->goods_preferential_start_time) == 0 or time() >= $goodsInfo->goods_preferential_start_time) ? true : false;
                $preferentialEnd   = (intval($goodsInfo->goods_preferential_end_time) == 0 or time() <= $goodsInfo->goods_preferential_end_time) ? true : false;
                $goodsInfo->goods_preferential_price = ($preferentialStart and $preferentialEnd and $goodsInfo->goods_preferential_price > 0) ? $goodsInfo->goods_preferential_price : 0;

                $goodsInfo->goods_shop_price = ($goodsInfo->goods_preferential_price <= 0 ? $goodsInfo->goods_shop_price : $goodsInfo->goods_preferential_price);
                //是否有会员价格，是否已经登录
                if($goodsInfo->goods_preferential_price <= 0 and isset($this->userData['group_id']) and $this->userData['group_id'] > 0) {
                    $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsInfo->goods_id, 'user_group_id'=>$this->userData['group_id'], 'goods_color'=>'', 'goods_size'=>'', 'adv_spec_tag_id'=>''));
                    if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $goodsInfo->goods_shop_price = $userGroupPrice->goods_user_group_price;
                }

                //商品库存显示
                $stock_state_id       = '';
                if ($goodsInfo->goods_stock <= $goodsInfo->goods_out_of_stock_set) {//当库存达到缺货时
                    $stock_state_id = $goodsInfo->goods_out_stock_state;
                } elseif($goodsInfo->goods_stock_state_open == 1) {//当启用库存状态显示，且库存充足
                    $stock_state_id = $goodsInfo->goods_stock_state;
                }
                if($stock_state_id != '') {//说明有文字库存显示，替换默认库存
                    $stockStateInfo         = $this->getDbshopTable('StockStateTable')->infoStockState(array('e.stock_state_id'=>$stock_state_id, 'e.language'=>$language));
                    $goodsInfo->goods_stock = $stockStateInfo->stock_state_name;
                }

                $goodsInfo = (array) $goodsInfo;
                $goodsInfo['goods_thumbnail_image'] = $this->createDbshopImageUrl($goodsInfo['goods_thumbnail_image']);
                $goodsInfo['goods_title_image']     = $this->createDbshopImageUrl($goodsInfo['goods_title_image']);
                $goodsInfo['goods_body']            = $this->createDbshopGoodsBody($goodsInfo['goods_body']);

                $goodsInfo['goods_price']               = ($goodsInfo['goods_price']>0 ? $this->getServiceLocator()->get('frontHelper')->shopPrice($goodsInfo['goods_price']) : 0);
                $goodsInfo['goods_shop_price']          = ($goodsInfo['goods_shop_price']>0 ? $this->getServiceLocator()->get('frontHelper')->shopPrice($goodsInfo['goods_shop_price']) : 0);
                $goodsInfo['goods_preferential_price']  = ($goodsInfo['goods_preferential_price']>0 ? $this->getServiceLocator()->get('frontHelper')->shopPrice($goodsInfo['goods_preferential_price']) : 0);

                //商品图片
                $goodsImages = $this->getDbshopTable('GoodsImageTable')->listImage(array('goods_id='.$goodsId, 'image_slide=1'))->toArray();
                if(is_array($goodsImages) and !empty($goodsImages)) {
                    $imageArray = array();
                    foreach($goodsImages as $imageValue) {
                        $imageArray[] = array(
                            'goods_image'       => $this->createDbshopImageUrl($imageValue['goods_title_image']),    //商品图片，大图
                            'goods_tmb_image'   => $this->createDbshopImageUrl($imageValue['goods_thumbnail_image']) //商品所谓图
                        );
                    }
                    $goodsInfo['images'] = $imageArray;
                }
                //商品自定义信息
                $goodsInfo['custom'] = $this->getDbshopTable('GoodsCustomTable')->listGoodsCustom(array('goods_id'=>$goodsId, 'custom_content_state'=>1));
                //商品销量
                $goodsInfo['goods_sales']  = $this->getDbshopTable('OrderGoodsTable')->countOrderGoodsNum(array('o.order_state!=0', 'dbshop_order_goods.goods_id='. $goodsId));
                //商品属性
                if($goodsInfo['attribute_group_id'] != '') {
                    $goodsInfo['attribute'] = $this->getAttributeArray($goodsInfo['attribute_group_id'], $goodsId);
                }
                //商品品牌
                if($goodsInfo['brand_id'] != '') {
                    $brandInfo = $this->getDbshopTable('GoodsBrandTable')->infoBrand(array('e.brand_id'=>$goodsInfo['brand_id'], 'e.language'=>$language));
                    if(!$brandInfo) $goodsInfo['brand_info'] = array();
                    else {
                        $goodsInfo['brand'] = (array) $brandInfo;
                        if(!empty($goodsInfo['brand']['brand_logo'])) $goodsInfo['brand']['brand_logo'] = $this->createDbshopImageUrl($goodsInfo['brand']['brand_logo'], false);
                    }
                }
                //关联商品
                $goodsInfo['relation_goods'] = $this->getDbshopTable('GoodsRelationTable')->listRelationGoods(array('dbshop_goods_relation.goods_id'=>$goodsId, 'g.goods_state'=>1, 'e.language'=>$this->getDbshopLang()->getLocale()), array("dbshop_goods_relation.relation_sort ASC"));
                if(is_array($goodsInfo['relation_goods']) and !empty($goodsInfo['relation_goods'])) {
                    foreach ($goodsInfo['relation_goods'] as $rKey => $rValue) {
                        $rValue['goods_thumbnail_image']    = $this->createDbshopImageUrl($rValue['goods_thumbnail_image']);
                        $rValue['goods_title_image']        = $this->createDbshopImageUrl($rValue['goods_title_image']);
                        $goodsInfo['relation_goods'][$rKey] = $rValue;
                    }
                }

                if($goodsInfo['goods_spec_type'] == 2) {
                    if(!empty($goodsInfo['adv_spec_group_id'])) {
                        $goodsInfo['goods_spec_group_array'] = array();
                        $goodsSpecGroupArray = $this->getDbshopTable('GoodsTagGroupTable')->listTagGroup(array("e.tag_group_id IN (".$goodsInfo['adv_spec_group_id'].")"));
                        if(is_array($goodsSpecGroupArray) and !empty($goodsSpecGroupArray)) {
                            foreach ($goodsSpecGroupArray as $gKey => $gValue) {
                                $goodsInfo['goods_spec_group_array'][$gValue['tag_group_id']] = $gValue;
                                unset($goodsSpecGroupArray[$gKey]);
                            }
                        }

                        $goodsSpecTagArray = $this->getDbshopTable('GoodsAdvSpecGroupTable')->listGoodsAdvSpecGroup(array('goods_id'=>$goodsId));
                        $specTagIdArray = array();//用于获取规格具体信息
                        if(!empty($goodsSpecTagArray)) {
                            foreach ($goodsSpecTagArray as $specTagValue) {
                                //$goodsInfo['spec_tag_id'][$specTagValue['group_id']] = explode(',', $specTagValue['selected_tag_id']);
                                $specTagIdArray[] = $specTagValue['selected_tag_id'];
                            }
                        }
                        //获取已经选中的规格信息
                        if(!empty($specTagIdArray)) {
                            $specTagArray = $this->getDbshopTable('GoodsTagTable')->simpleListGoodsTag(array('e.tag_id IN ('.implode(',', $specTagIdArray).')'));
                            if(!empty($specTagArray)) {
                                foreach ($specTagArray as $sTagValue) {
                                    $array['spec_tag_id'][$sTagValue['tag_group_id']][] = $sTagValue['tag_id'];

                                    $goodsInfo['goods_spec_group_array'][$sTagValue['tag_group_id']]['spec_tag'][] = $sTagValue;
                                    $goodsInfo['spec_tag'][$sTagValue['tag_id']] = $sTagValue;
                                }
                            }
                        }
                    }
                } else {
                    //颜色扩展
                    $goodsColor = $this->getDbshopTable('GoodsPriceExtendTable')->infoPriceExtend(array('extend_type'=>'one', 'goods_id'=>$goodsId, 'language'=>$language));
                    if($goodsColor) {
                        $goodsColorArray = $this->getDbshopTable('GoodsPriceExtendColorTable')->listPriceExtendColor(array('goods_id'=>$goodsId, 'extend_id'=>$goodsColor->extend_id));
                        if(is_array($goodsColorArray) and !empty($goodsColorArray)) {
                            $colorArray['name']             = $goodsColor->extend_name;
                            $colorArray['extend_show_type'] = $goodsColor->extend_show_type;
                            foreach($goodsColorArray as $colorValue) {
                                $colorArray['list'][] = array(
                                    'value'   => $colorValue['color_value'],
                                    'info'    => $colorValue['color_info']
                                );
                            }
                            $goodsInfo['color'] = $colorArray;
                        }
                    }
                    //尺寸扩展
                    $goodsSize   = $this->getDbshopTable('GoodsPriceExtendTable')->infoPriceExtend(array('extend_type'=>'two', 'goods_id'=>$goodsId, 'language'=>$language));
                    if($goodsSize) {
                        $goodsSizeArray = $this->getDbshopTable('GoodsPriceExtendSizeTable')->listPriceExtendSize(array('goods_id'=>$goodsId, 'extend_id'=>$goodsSize->extend_id));
                        if(is_array($goodsSizeArray) and !empty($goodsSizeArray)) {
                            $sizeArray['name'] = $goodsSize->extend_name;
                            $sizeArray['extend_show_type'] = $goodsSize->extend_show_type;
                            foreach($goodsSizeArray as $sizeValue) {
                                $sizeArray['list'][] = array(
                                    'value'    => $sizeValue['size_value'],
                                    'info'     => $sizeValue['size_info'],
                                );
                            }
                            $goodsInfo['size'] = $sizeArray;
                        }
                    }
                }

                //事件驱动，显示商品信息时的一些抛出
                $response = $this->getEventManager()->trigger('goods.info.front.post', $this, array('values'=>array('goods_info'=>(object)$goodsInfo)));
                if(!$response->isEmpty()) {
                    $num = $response->count();
                    for($i = 0; $i < $num; $i++) {
                        $preArray = $response->offsetGet($i);
                        if(!empty($preArray)) $goodsInfo[key($preArray)] = current($preArray);
                        unset($preArray);
                    }
                }
                //对会员组价格显示的判断处理
                $userGroupPriceShowState = $this->getServiceLocator()->get('frontHelper')->getDbshopGoodsIni('dbshop_goods_usergroup_price_show');
                if(isset($goodsInfo['group_price']) && !empty($goodsInfo['group_price']) && $userGroupPriceShowState != 1) $goodsInfo['group_price'] = array();

                return $this->createJsonData($goodsInfo);
            }
        }
        return $this->createJsonData($goodsInfo);
    }
    /**
     * 获取规格商品对应的商品信息（color_value和size_value 、spec_tag_id_str两个必须有其中一个必填）
     * post
     * goods_id     必填，商品id
     * color_value  必填，颜色值
     * size_value   必填，尺寸值
     * spec_tag_id_str 必填，高级规格中的已经选中的规格id字符串
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return DbJsonModel
     */
    public function goodsSpecInfoAction()
    {
        $goodsId    = isset($this->postData['goods_id'])    ? (int) $this->postData['goods_id'] : 0;
        $colorValue = isset($this->postData['color_value']) ? trim($this->postData['color_value']) : '';
        $sizeValue  = isset($this->postData['size_value'])  ? trim($this->postData['size_value']) : '';
        $specTagIdStr= isset($this->postData['spec_tag_id_str'])  ? trim($this->postData['spec_tag_id_str']) : '';

        $goodsSpec  = array();
        if($goodsId > 0 and ((!empty($colorValue) and !empty($sizeValue)) or !empty($specTagIdStr))) {
            $stockNum = '';
            $groupPriceArray  = array();
            $goodsInfo   = $this->getDbshopTable('GoodsTable')->oneGoodsInfo(array('goods_id'=>$goodsId));
            $goodsItem   = $goodsInfo->goods_item;//商品货号

            if($goodsInfo->goods_spec_type == 2) {//高级规格模式
                $specTagIdArray = explode(',', $specTagIdStr);
                $specTagIdArray = array_filter($specTagIdArray);
                sort($specTagIdArray);
                $specTagIdStr = implode(',', $specTagIdArray);
                $extendGoods = $this->getDbshopTable('GoodsPriceExtendGoodsTable')->InfoPriceExtendGoods(array('goods_id'=>$goodsId, 'adv_spec_tag_id'=>$specTagIdStr));
                if($extendGoods) {
                    $goodsItem = $extendGoods->goods_extend_item;//商品货号，如果规格存在，覆盖之前值
                    //库存显示处理
                    $stockNum  = $extendGoods->goods_extend_stock;//默认库存
                    $stock_state_id= '';
                    if ($stockNum <= $goodsInfo->goods_out_of_stock_set) {//当库存达到缺货时
                        $stock_state_id = $goodsInfo->goods_out_stock_state;
                    } elseif($goodsInfo->goods_stock_state_open == 1) {//当启用库存状态显示，且库存充足
                        $stock_state_id = $goodsInfo->goods_stock_state;
                    }
                    if($stock_state_id != '') {//说明有文字库存显示，替换默认库存
                        $stockStateInfo = $this->getDbshopTable('StockStateTable')->infoStockState(array('e.stock_state_id'=>$stock_state_id, 'e.language'=>$this->getDbshopLang()->getLocale()));
                        $stockNum       = $stockStateInfo->stock_state_name;
                    }
                    //判断是否登录，是否有会员组价格
                    if(isset($this->userData['group_id']) and $this->userData['group_id'] > 0) {
                        $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsId, 'user_group_id'=>$this->userData['group_id'], 'adv_spec_tag_id'=>$specTagIdStr));
                        if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $extendGoods->goods_extend_price = $userGroupPrice->goods_user_group_price;
                    }
                    $goodsPrice    = $this->getServiceLocator()->get('frontHelper')->shopPrice($extendGoods->goods_extend_price);
                    //获取会员组价格
                    $groupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->listGoodsUsergroupPrice(array('goods_id'=>$goodsId, 'adv_spec_tag_id'=>$specTagIdStr));
                    if(is_array($groupPrice) and !empty($groupPrice)) {
                        foreach($groupPrice as $groupPriceValue) {
                            if($groupPriceValue['goods_user_group_price'] > 0) $groupPriceArray[$groupPriceValue['user_group_id']] = array('group_name'=>$groupPriceValue['group_name'], 'group_price'=>$this->getServiceLocator()->get('frontHelper')->shopPrice($groupPriceValue['goods_user_group_price']));
                        }
                    }

                }
            } else {//普通规格模式
                $extendGoods = $this->getDbshopTable('GoodsPriceExtendGoodsTable')->InfoPriceExtendGoods(array('goods_id'=>$goodsId, 'goods_color'=>$colorValue, 'goods_size'=>$sizeValue));
                if($extendGoods) {
                    $goodsItem = $extendGoods->goods_extend_item;//商品货号，如果规格存在，覆盖之前值

                    //库存显示处理
                    $stockNum      = $extendGoods->goods_extend_stock;//默认库存
                    $stock_state_id= '';
                    if ($stockNum <= $goodsInfo->goods_out_of_stock_set) {//当库存达到缺货时
                        $stock_state_id = $goodsInfo->goods_out_stock_state;
                    } elseif($goodsInfo->goods_stock_state_open == 1) {//当启用库存状态显示，且库存充足
                        $stock_state_id = $goodsInfo->goods_stock_state;
                    }
                    if($stock_state_id != '') {//说明有文字库存显示，替换默认库存
                        $stockStateInfo = $this->getDbshopTable('StockStateTable')->infoStockState(array('e.stock_state_id'=>$stock_state_id, 'e.language'=>$this->getDbshopLang()->getLocale()));
                        $stockNum       = $stockStateInfo->stock_state_name;
                    }

                    //判断是否登录，是否有会员组价格
                    if(isset($this->userData['group_id']) and $this->userData['group_id'] > 0) {
                        $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsId, 'user_group_id'=>$this->userData['group_id'], 'goods_color'=>$colorValue, 'goods_size'=>$sizeValue));
                        if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $extendGoods->goods_extend_price = $userGroupPrice->goods_user_group_price;
                    }
                    $goodsPrice    = $this->getServiceLocator()->get('frontHelper')->shopPrice($extendGoods->goods_extend_price);
                    //获取会员组价格
                    $groupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->listGoodsUsergroupPrice(array('goods_id'=>$goodsId, 'goods_color'=>$colorValue, 'goods_size'=>$sizeValue));
                    if(is_array($groupPrice) and !empty($groupPrice)) {
                        foreach($groupPrice as $groupPriceValue) {
                            if($groupPriceValue['goods_user_group_price'] > 0) $groupPriceArray[$groupPriceValue['user_group_id']] = array('group_name'=>$groupPriceValue['group_name'], 'group_price'=>$this->getServiceLocator()->get('frontHelper')->shopPrice($groupPriceValue['goods_user_group_price']));
                        }
                    }
                }
            }


            return $this->createJsonData(array(
                'goods_item'        => $goodsItem,
                'goods_shop_price'  => $goodsPrice,
                'goods_stock'       => $stockNum,
                'goods_integral'    => $extendGoods->goods_extend_integral,
                'goods_user_group_price' => $groupPriceArray
            ));
        }
        return $this->createJsonData($goodsSpec);
    }
    /**
     * 商品咨询列表（分页）
     * get
     * goods_id 必填，商品id
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * @return DbJsonModel
     */
    public function goodsAskAction()
    {
        $goodsId    = isset($this->getData['goods_id'])    ? (int) $this->getData['goods_id'] : 0;
        $goodsAsk   = array();
        if($goodsId > 0) {
            $array  = $this->pageAndQtyAndStart();

            $where  = array('dbshop_goods_ask.ask_show_state'=>1, 'dbshop_goods_ask.goods_id'=>$goodsId, 'e.language'=>$this->getDbshopLang()->getLocale());
            $array['where']  = $where;

            $goodsAsk = $this->getDbshopTable('ApiGoodsAskTable')->listGoodsAsk($array);
            if(is_array($goodsAsk) and !empty($goodsAsk)) {
                foreach ($goodsAsk as $key => $value) {
                    $value['ask_writer'] = $this->getServiceLocator()->get('frontHelper')->userNameHide($value['ask_writer']);
                    if(!empty($value['ask_time'])) $value['ask_date_time'] = date("Y-m-d H:i:s", $value['ask_time']);
                    if(!empty($value['reply_ask_time'])) $value['reply_ask_date_time'] = date("Y-m-d H:i:s", $value['reply_ask_time']);
                    $goodsAsk[$key] = $value;
                }
            }
            return $this->createJsonData($goodsAsk);
        }
        return $this->createJsonData($goodsAsk);
    }
    /**
     * 商品评价列表（分页）
     * get
     * goods_id 必填，商品id
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * @return DbJsonModel
     */
    public function goodsCommentAction()
    {
        $goodsId        = isset($this->getData['goods_id'])    ? (int) $this->getData['goods_id'] : 0;
        $goodsComment   = array();
        if($goodsId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where']     = array('goods_id'=>$goodsId, 'comment_show_state'=>1);
            $array['avatar']    = true;

            $goodsComment = $this->getDbshopTable('ApiGoodsCommentTable')->listGoodsComment($array);
            if(is_array($goodsComment) and !empty($goodsComment)) {
                foreach ($goodsComment as $key => $value) {
                    $value['comment_writer'] = $this->getServiceLocator()->get('frontHelper')->userNameHide($value['comment_writer']);
                    if(!empty($value['comment_time'])) $value['comment_date_time'] = date("Y-m-d H:i:s", $value['comment_time']);
                    if(!empty($value['reply_time'])) $value['reply_date_time'] = date("Y-m-d H:i:s", $value['reply_time']);
                    $goodsComment[$key] = $value;
                }
            }
            return $this->createJsonData($goodsComment);
        }
        return $this->createJsonData($goodsComment, 'error');
    }

    /**
     * 商品优惠券列表
     * get
     * goods_id 必填，商品id
     * user_token  选填，用户登录状态时传此值
     *
     * @return DbJsonModel
     */
    public function goodsCouponListAction()
    {
        $array = array();

        $goodsId    = isset($this->getData['goods_id'])    ? (int) $this->getData['goods_id'] : 0;
        $userGroup = $this->getDbshopTable('UserGroupTable')->listUserGroup();

        $typeArray = array(
            'all_goods'     => $this->getDbshopLang()->translate('所有商品'),
            'class_goods'   => $this->getDbshopLang()->translate('商品分类'),
            'brand_goods'   => $this->getDbshopLang()->translate('商品品牌')
        );

        //如果用户登录，这里输出获取过的优惠券
        $userId = isset($this->userData['user_id']) ? (int) $this->userData['user_id'] : 0;
        $userCouponIdArray = array();
        if($userId > 0) {
            $userCoupon = $this->getDbshopTable('UserCouponTable')->useUserCoupon(array('user_id'=>$userId, 'get_coupon_type'=>'click'));
            if(!empty($userCoupon)) {
                foreach ($userCoupon as $uValue) {
                    $userCouponIdArray[$uValue['coupon_id']] = $uValue['coupon_id'];
                }
            }
        }

        $newTime = time();
        if($goodsId > 0) {
            $goodsCouponArray = array();
            $array['goods_id'] = $goodsId;
            $goodsInfo  = $this->getDbshopTable('GoodsTable')->infoGoods(array('dbshop_goods.goods_id'=>$goodsId, 'e.language'=>$this->getDbshopLang()->getLocale()));
            if($goodsInfo) {
                //是否有对应商品的优惠券
                $goodsCoupon = $this->getDbshopTable('CouponTable')->couponArray(array('get_coupon_type'=>'click', 'coupon_state'=>1, 'coupon_goods_type'=>'individual_goods', 'coupon_goods_body like \'%"'.$goodsInfo->goods_id.'"%\''));
                if($goodsCoupon) {
                    foreach ($goodsCoupon as $cKey => $cValue) {
                        if(!empty($cValue['get_coupon_start_time']) && $newTime < $cValue['get_coupon_start_time']) continue;
                        if(!empty($cValue['get_coupon_end_time']) && $newTime > $cValue['get_coupon_end_time']) continue;

                        $cValue['user_group'] = $this->getUserGroup($cValue, $userGroup);

                        $cValue['coupon_goods_type']    = $typeArray[$cValue['coupon_goods_type']];
                        $cValue['coupon_get_state']     = empty($userCouponIdArray) ? 'false' : (isset($userCouponIdArray[$cValue['coupon_id']]) ? 'true' : 'false');

                        $goodsCouponArray[] = $cValue;
                    }
                }

                //是否有对应商品品牌的优惠券
                if($goodsInfo->brand_id) {
                    $goodsCoupon = $this->getDbshopTable('CouponTable')->couponArray(array('get_coupon_type'=>'click', 'coupon_state'=>1, 'coupon_goods_type'=>'brand_goods', 'coupon_goods_body like \'%"'.$goodsInfo->brand_id.'"%\''));
                    if($goodsCoupon) {
                        foreach ($goodsCoupon as $cKey => $cValue) {
                            if(!empty($cValue['get_coupon_start_time']) && $newTime < $cValue['get_coupon_start_time']) continue;
                            if(!empty($cValue['get_coupon_end_time']) && $newTime > $cValue['get_coupon_end_time']) continue;

                            $cValue['user_group'] = $this->getUserGroup($cValue, $userGroup);

                            $cValue['coupon_goods_type']    = $typeArray[$cValue['coupon_goods_type']];
                            $cValue['coupon_get_state']     = empty($userCouponIdArray) ? 'false' : (isset($userCouponIdArray[$cValue['coupon_id']]) ? 'true' : 'false');

                            $goodsCouponArray[] = $cValue;
                        }
                    }
                }

                $goodsClassIdArray = $this->getDbshopTable('GoodsInClassTable')->listGoodsInClass(array('goods_id'=>$goodsInfo->goods_id));
                if(!empty($goodsClassIdArray)) {
                    $CouponArray = $this->getDbshopTable('CouponTable')->couponArray(array('get_coupon_type'=>'click', 'coupon_state'=>1, 'coupon_goods_type'=>'class_goods'));

                    if($CouponArray) {
                        foreach ($CouponArray as $cKey => $cValue) {
                            if(!empty($cValue['get_coupon_start_time']) && $newTime < $cValue['get_coupon_start_time']) continue;
                            if(!empty($cValue['get_coupon_end_time']) && $newTime > $cValue['get_coupon_end_time']) continue;

                            $cArray = unserialize($cValue['coupon_goods_body']);
                            if(!empty($cArray)) {
                                $result = array_intersect($goodsClassIdArray, $cArray);
                                if(!empty($result)) {
                                    $cValue['user_group'] = $this->getUserGroup($cValue, $userGroup);

                                    $cValue['coupon_goods_type']    = $typeArray[$cValue['coupon_goods_type']];
                                    $cValue['coupon_get_state']     = empty($userCouponIdArray) ? 'false' : (isset($userCouponIdArray[$cValue['coupon_id']]) ? 'true' : 'false');

                                    $goodsCouponArray[] = $cValue;
                                }
                            }
                        }
                    }
                }

                $array['goods_coupon'] = $goodsCouponArray;

            }
        }

        $generalCouponArray = array();
        $generalCoupon = $this->getDbshopTable('CouponTable')->couponArray(array('get_coupon_type'=>'click', 'coupon_goods_type'=>'all_goods', 'coupon_state'=>1));
        if(!empty($generalCoupon)) {
            foreach ($generalCoupon as $cKey => $cValue) {
                if(!empty($cValue['get_coupon_start_time']) && $newTime < $cValue['get_coupon_start_time']) continue;
                if(!empty($cValue['get_coupon_end_time']) && $newTime > $cValue['get_coupon_end_time']) continue;

                $cValue['user_group'] = $this->getUserGroup($cValue, $userGroup);

                $cValue['coupon_goods_type']    = $typeArray[$cValue['coupon_goods_type']];
                $cValue['coupon_get_state']     = empty($userCouponIdArray) ? 'false' : (isset($userCouponIdArray[$cValue['coupon_id']]) ? 'true' : 'false');

                $generalCouponArray[] = $cValue;
            }
        }
        $array['general_coupon'] = $generalCouponArray;


        return $this->createJsonData($array);
    }

    /**
     * 点击获取优惠券
     * post
     * user_token   必填，用户登录状态时传此值
     * coupon_id    必填，优惠券id
     *
     * @return JsonModel
     */
    public function clickGetCouponAction()
    {
        $couponId   = isset($this->postData['coupon_id']) ? (int) $this->postData['coupon_id'] : 0;
        $userId     = isset($this->userData['user_id']) ? (int) $this->userData['user_id'] : 0;

        if($userId <= 0) return $this->createJson('error', $this->getDbshopLang()->translate('登录后，才能进行领取！'));

        $couponInfo = $this->getDbshopTable('CouponTable')->infoCoupon(array('get_coupon_type'=>'click', 'coupon_state'=>1, 'coupon_id'=>$couponId));
        if($couponInfo) {
            if($couponInfo->get_user_type == 'user_group') {//检查会员组是否有资格获取
                $couponUserGroup = unserialize($couponInfo->get_user_group);
                if(empty($couponUserGroup)) {
                    return $this->createJson('error', $this->getDbshopLang()->translate('您的等级不在获取该优惠券的范围内！'));
                }
                elseif (!in_array($this->userData['group_id'], $couponUserGroup)) {
                    return $this->createJson('error', $this->getDbshopLang()->translate('您的等级不在获取该优惠券的范围内！'));
                }
            }

            $nowTime = time();
            if(!empty($couponInfo->get_coupon_start_time) and $nowTime < $couponInfo->get_coupon_start_time) return $this->createJson('error', $this->getDbshopLang()->translate('获取时间未到！'));
            if(!empty($couponInfo->get_coupon_end_time) and $nowTime > $couponInfo->get_coupon_end_time) return $this->createJson('error', $this->getDbshopLang()->translate('获取时间已过！'));

            //检查是否已经获取过了
            $userCoupon = $this->getDbshopTable('UserCouponTable')->infoUserCoupon(array('coupon_id'=>$couponId, 'user_id'=>$userId));
            if($userCoupon) return $this->createJson('error', $this->getDbshopLang()->translate('您已经获取过该优惠券，不能重复获取！'));

            $addUserCoupon = array(
                'coupon_use_state'  => 1,           //优惠券状态
                'user_id'           => $userId,     //会员id
                'user_name'         => $this->userData['user_name'],  //会员名称
                'get_time'          => time(),      //获取时间
                'coupon_id'         => $couponId,   //优惠券id
                'coupon_name'       => $couponInfo->coupon_name,   //优惠券名称
                'coupon_info'       => $couponInfo->coupon_info,//优惠券描述
            );
            if(!empty($couponInfo->coupon_start_time)) $addUserCoupon['coupon_start_use_time'] = $couponInfo->coupon_start_time;
            if(!empty($couponInfo->coupon_end_time)) $addUserCoupon['coupon_expire_time'] = $couponInfo->coupon_end_time;
            $this->getDbshopTable('UserCouponTable')->addUserCoupon($addUserCoupon);
            return $this->createJson('success', $this->getDbshopLang()->translate('优惠券获取成功！'));
        }
        return $this->createJson('error', $this->getDbshopLang()->translate('无优惠券领取！'));
    }

    /**
     * 收藏商品
     * post
     * goods_id 必填，商品id
     * class_id 必填，商品分类id
     * user_token    必填，用户登录状态时传此值
     * @return JsonModel|DbJsonModel
     */
    public function addGoodsFavoritesAction()
    {
        $goodsId    = isset($this->postData['goods_id']) ? (int) $this->postData['goods_id'] : 0;
        $classId    = isset($this->postData['class_id']) ? (int) $this->postData['class_id'] : 0;
        $status     = 'error';
        if (empty($this->userData['user_id'])) {
            $msg  = $this->getDbshopLang()->translate('您还没有登录，无法收藏商品！');
        }
        else $msg = $this->getDbshopLang()->translate('收藏商品失败！');

        if($goodsId >0 and $classId > 0 and !empty($this->userData['user_id'])) {
            $favoritesInfo = $this->getDbshopTable('UserFavoritesTable')->infoFavorites(array('goods_id'=>$goodsId, 'user_id'=>$this->userData['user_id']));
            if($favoritesInfo) {
                $msg = $this->getDbshopLang()->translate('您已经收藏过该商品！');
            } else {
                $favoriteId = $this->getDbshopTable('UserFavoritesTable')->addFavorites(array('class_id'=>$classId, 'goods_id'=>$goodsId, 'user_id'=>$this->userData['user_id']));
                return $this->createJsonData(array('favorites_id'=>$favoriteId), 'success', $this->getDbshopLang()->translate('该商品成功加入收藏！'));
            }
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 添加商品咨询
     * post
     * goods_id 必填，商品id
     * goods_ask_content    必填，商品咨询内容
     * user_token    非必填，用户登录状态时传此值
     * @return JsonModel
     */
    public function addGoodsAskAction()
    {
        $goodsId    = isset($this->postData['goods_id']) ? (int) $this->postData['goods_id'] : 0;
        $goodsAsk   = isset($this->postData['goods_ask_content']) ? trim($this->postData['goods_ask_content']) : '';
        $userName   = isset($this->userData['user_name']) ? $this->userData['user_name'] : '';
        $status     = 'error';
        $msg        = $this->getDbshopLang()->translate('添加商品咨询失败！');

        if($goodsId > 0 and !empty($goodsAsk)) {
            //保存商品咨询信息
            $postArray['goods_id']       = $goodsId;
            $postArray['ask_content']    = $this->filterEmoji($goodsAsk);
            $postArray['ask_time']       = time();
            $postArray['ask_writer']     = $userName == '' ? $this->getDbshopLang()->translate('游客') : $userName;
            $postArray['ask_show_state'] = 0;
            if($this->getDbshopTable('GoodsAskTable')->addGoodsAsk($postArray)) {
                /*===========================商品咨询提醒邮件发送,必须是登陆用户才可以有此服务===========================*/
                $buyerEmail = $this->getServiceLocator()->get('frontHelper')->getSendMessageBuyerEmail('goods_ask_state', $this->userData['user_email']);
                $adminEmail = $this->getServiceLocator()->get('frontHelper')->getSendMessageAdminEmail('goods_ask_state');
                if($this->userData['user_name'] != '' and ($buyerEmail != '' or $adminEmail != '')) {
                    $sendMessageBody = $this->getServiceLocator()->get('frontHelper')->getSendMessageBody('goods_ask');
                    if($sendMessageBody != '') {
                        $sendArray = array();
                        $sendArray['shopname']     = $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name');
                        $sendArray['shopurl']      = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost() . $this->url()->fromRoute('shopfront/default');
                        $sendArray['askusername']  = $this->userData['user_name'];
                        $sendArray['asktime']      = $postArray['ask_time'];

                        $goodsInfo   = $this->getDbshopTable('GoodsTable')->infoGoods(array('dbshop_goods.goods_id'=>$goodsId, 'e.language'=>$this->getDbshopLang()->getLocale()));
                        $inClass     = $this->getDbshopTable('GoodsInClassTable')->oneGoodsInClass(array('dbshop_goods_in_class.goods_id'=>$goodsId, 'c.class_state'=>1));
                        $sendArray['goodsname']  = '<a href="'. $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost() . $this->url()->fromRoute('frontgoods/default', array('goods_id'=>$goodsId, 'class_id'=>$inClass[0]['class_id'])).'" target="_blank">' . $goodsInfo->goods_name . '</a>';

                        $sendArray['subject']       = $sendArray['shopname'] . '|' . $this->getDbshopLang()->translate('新的商品咨询') . '|' . $goodsInfo->goods_name;
                        $sendArray['send_mail'][]   = $buyerEmail;
                        $sendArray['send_mail'][]   = $adminEmail;
                        $sendMessageBody            = $this->getServiceLocator()->get('frontHelper')->createSendMessageContent($sendArray, $sendMessageBody);
                        try {
                            $sendState = $this->getServiceLocator()->get('shop_send_mail')->SendMesssageMail($sendArray, $sendMessageBody);
                            $sendState = ($sendState ? 1 : 2);
                        } catch (\Exception $e) {
                            $sendState = 2;
                        }
                        //记录给用户发的电邮
                        if($sendArray['send_mail'][0] != '') {
                            $sendLog = array(
                                'mail_subject' => $sendArray['subject'],
                                'mail_body'    => $sendMessageBody,
                                'send_time'    => time(),
                                'user_id'      => $this->userData['user_id'],
                                'send_state'   => $sendState
                            );
                            $this->getDbshopTable('UserMailLogTable')->addUserMailLog($sendLog);
                        }
                    }
                }
                /*===========================商品咨询提醒邮件发送,必须是登陆用户才可以有此服务===========================*/

                $status = 'success';
                $msg    = $this->getDbshopLang()->translate('添加商品咨询成功！');
            }
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 商品搜索
     * get
     * keywords 非必填，可以是商品中的任何文字检索，用空格分开可精确检索
     * sort_type选填，默认是按照该分类的商品排序设置进行排序（time_asc、time_desc、click_asc、click_desc、price_asc、price_desc、sale_asc、sale_desc）
     * start_price  选填，检索价格区间，开始价格
     * end_price    选填，检索价格区间，结束价格
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return JsonModel
     */
    public function searchGoodsAction()
    {
        $sortType   = isset($this->getData['sort_type']) ? trim($this->getData['sort_type']) : '';
        $startPrice = isset($this->getData['start_price']) ? floatval($this->getData['start_price']) : 0;
        $endPrice   = isset($this->getData['end_price']) ? floatval($this->getData['end_price']) : 0;

        $keywords = isset($this->getData['keywords']) ? htmlentities($this->getData['keywords'], ENT_QUOTES, "UTF-8") : '';
        $array  = $this->pageAndQtyAndStart();
        $array['where']         = array('goods_name'=>$keywords, 'goods_state'=>1);
        $array['goods_state']   = 1;
        $array['order']         = '';

        //排序
        if(!empty($sortType) and in_array($sortType, array('time_asc', 'time_desc', 'click_asc', 'click_desc', 'price_asc', 'price_desc', 'sale_asc', 'sale_desc'))) {
            $sortArray = array(
                'time_asc'      => 'dbshop_goods.goods_add_time ASC',
                'time_desc'     => 'dbshop_goods.goods_add_time DESC',
                'click_asc'     => 'dbshop_goods.goods_click ASC',
                'click_desc'    => 'dbshop_goods.goods_click DESC',
                'price_asc'     => 'dbshop_goods.goods_shop_price+1 ASC',
                'price_desc'    => 'dbshop_goods.goods_shop_price+1 DESC',
                'sale_asc'      => 'buy_num ASC',
                'sale_desc'     => 'buy_num DESC'
            );
            $array['order'] = $sortArray[$sortType];
        }
        //价格检索
        if($startPrice > 0) $array['where']['start_goods_price'] = $startPrice;
        if($endPrice > 0) $array['where']['end_goods_price'] = $endPrice;

        $array['group_id'] = (isset($this->userData['group_id']) and $this->userData['group_id'] > 0) ? $this->userData['group_id'] : 0;

        //获取商品索引的状态，是否开启
        $goodsIndexState = $this->getServiceLocator()->get('frontHelper')->getDbshopGoodsIni('goods_index', '');
        if($goodsIndexState)
            $goodsList  = $this->getDbshopTable('ApiGoodsIndexTable')->searchGoods($array);
        else
            $goodsList  = $this->getDbshopTable()->searchGoods($array);

        if(is_array($goodsList) and !empty($goodsList)) {//进行图片地址转换，转换为公网可访问地址
            foreach($goodsList as $key => $value) {
                $goodsList[$key]['goods_thumbnail_image'] = $this->createDbshopImageUrl($value['goods_thumbnail_image']);
                $goodsList[$key]['goods_shop_price'] = (isset($value['group_price']) and $value['group_price'] > 0)
                    ? $this->getServiceLocator()->get('frontHelper')->shopPrice($value['group_price'])
                    : $this->getServiceLocator()->get('frontHelper')->shopPrice($value['goods_shop_price']);

                unset($goodsList[$key]['goods_body']);
            }
        }

        return $this->createJsonData($goodsList);
    }
    /**
     * 品牌列表
     * get
     * @return JsonModel
     */
    public function goodsBrandAction()
    {
        $brandList = $this->getDbshopTable('GoodsBrandTable')->listGoodsBrand();
        if(is_array($brandList) and !empty($brandList)) {
            foreach ($brandList as $key => $value) {
                $brandLogo = !empty($value['brand_logo']) ? $value['brand_logo'] : $this->getServiceLocator()->get('frontHelper')->getGoodsUploadIni('brand', 'brand_image_default');
                $brandList[$key]['brand_logo'] = $this->createDbshopImageUrl($brandLogo, false);
            }
        }
        return $this->createJsonData($brandList);
    }
    /**
     * 获取单个品牌信息
     * post
     * brand_id
     * @return DbJsonModel
     */
    public function brandInfoAction()
    {
        $brandId    = isset($this->postData['brand_id']) ? (int) $this->postData['brand_id'] : 0;
        $brandInfo  = '';
        if($brandId > 0) {
            $brandInfo = $this->getDbshopTable('GoodsBrandTable')->infoBrand(array('dbshop_goods_brand.brand_id'=>$brandId));
            if(!empty($brandInfo)) {
                $brandLogo = !empty($brandInfo->brand_logo) ? $brandInfo->brand_logo : $this->getServiceLocator()->get('frontHelper')->getGoodsUploadIni('brand', 'brand_image_default');
                $brandInfo->brand_logo = $this->createDbshopImageUrl($brandInfo->brand_logo, false);
            }
        }
        return $this->createJsonData($brandInfo);
    }
    /**
     * 品牌商品列表
     * get
     * brand_id 必填，品牌id
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return JsonModel
     */
    public function brandGoodsListAction()
    {
        $brandId    = isset($this->getData['brand_id']) ? (int) $this->getData['brand_id'] : 0;
        $brandGoodsList = array();
        if($brandId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'] = array('brand_id'=>$brandId, 'goods_state'=>1);
            $array['order'] = '';
            $array['group_id'] = (isset($this->userData['group_id']) and $this->userData['group_id'] > 0) ? $this->userData['group_id'] : 0;

            $brandGoodsList = $this->getDbshopTable()->searchGoods($array);
            if(is_array($brandGoodsList) and !empty($brandGoodsList)) {
                foreach($brandGoodsList as $key => $value) {
                    $brandGoodsList[$key]['goods_thumbnail_image'] = $this->createDbshopImageUrl($value['goods_thumbnail_image']);
                    $brandGoodsList[$key]['goods_shop_price'] = (isset($value['group_price']) and $value['group_price'] > 0)
                        ? $this->getServiceLocator()->get('frontHelper')->shopPrice($value['group_price'])
                        : $this->getServiceLocator()->get('frontHelper')->shopPrice($value['goods_shop_price']);

                    unset($brandGoodsList[$key]['goods_body']);
                }
            }
        }
        return $this->createJsonData($brandGoodsList);
    }
    /*============================================商品相关============================================*/

    /*============================================购物车相关============================================*/
    /**
     * 添加商品进购物车
     * post
     * goods_id 必填，商品id
     * class_id 必填，分类id
     * buy_goods_num 必填，购买数量
     * user_unionid  必填，用户唯一标识，由客户端生成
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * color_value   选填，颜色标记，只有在购买的商品有此值时，才需要传递
     * size_value    选填，尺寸标记，只有在购买的商品有此值时，才需要传递
     * spec_tag_id_str 选填，高级规格选中的id字符串
     * @return JsonModel
     */
    public function addCartAction()
    {
        $goodsId        = isset($this->postData['goods_id']) ? (int) $this->postData['goods_id'] : 0;
        $classId        = isset($this->postData['class_id']) ? (int) $this->postData['class_id'] : 0;
        $buyNum         = isset($this->postData['buy_goods_num']) ? (int) $this->postData['buy_goods_num'] : 0;

        $colorValue     = isset($this->postData['color_value']) ? trim($this->postData['color_value']) : '';
        $sizeValue      = isset($this->postData['size_value'])  ? trim($this->postData['size_value'])  : '';
        $specTagIdStr   = isset($this->postData['spec_tag_id_str']) ? trim($this->postData['spec_tag_id_str']) : '';

        $userUnionid    = isset($this->postData['user_unionid'])  ? trim($this->postData['user_unionid'])  : '';//用户唯一标识用户设备处生成

        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('购物车添加失败！');

        if($classId > 0 and $goodsId > 0 and $buyNum > 0 and !empty($userUnionid)) {
            //事件监听，抛出错误信息
            $response = $this->getEventManager()->trigger('cart.add.front.pre', $this, array('values'=>array('post'=>$this->postData, 'user'=>$this->userData)));
            if(!$response->isEmpty()) {
                $num = $response->count();
                for($i = 0; $i < $num; $i++) {
                    $preArray = $response->offsetGet($i);
                    if(isset($preArray['state']) and !$preArray['state']) {
                        return $this->createJson($status, $preArray['message']);
                        //exit($preArray['message']);
                    }
                }
            }

            $userGroupId = isset($this->userData['group_id']) ? $this->userData['group_id'] : 0;
            //检查基础商品是否存在，并且状态是开启状态
            $goodsInfo = $this->getDbshopTable('GoodsTable')->infoGoods(array('dbshop_goods.goods_id'=>$goodsId, 'dbshop_goods.goods_state'=>1));
            if(!$goodsInfo) $msg = $this->getDbshopLang()->translate('商品不存在，无法加入购物车！');
            else {
                //判断优惠价格是否存在，是否过期
                $preferentialStart = (intval($goodsInfo->goods_preferential_start_time) == 0 or time() >= $goodsInfo->goods_preferential_start_time) ? true : false;
                $preferentialEnd   = (intval($goodsInfo->goods_preferential_end_time) == 0 or time() <= $goodsInfo->goods_preferential_end_time) ? true : false;
                $goodsInfo->goods_preferential_price = ($preferentialStart and $preferentialEnd and $goodsInfo->goods_preferential_price > 0) ? $goodsInfo->goods_preferential_price : 0;

                if($goodsInfo->goods_spec_type == 2) {//规格高级模式
                    if(!empty($specTagIdStr)) {
                        $specTagIdArray = explode(',', $specTagIdStr);
                        $specTagIdArray = array_filter($specTagIdArray);
                        sort($specTagIdArray);
                        $specTagIdStr = implode(',', $specTagIdArray);
                        $extendGoods = $this->getDbshopTable('GoodsPriceExtendGoodsTable')->InfoPriceExtendGoods(array('adv_spec_tag_id'=>$specTagIdStr, 'goods_id'=>$goodsId));
                        if(!$extendGoods) return $this->createJson('error', $this->getDbshopLang()->translate('商品没有您选择的规格存在，无法加入购物车！'));
                        $goodsInfo->goods_stock      = $extendGoods->goods_extend_stock;
                        $goodsInfo->goods_item       = $extendGoods->goods_extend_item;
                        $goodsInfo->goods_integral_num = $extendGoods->goods_extend_integral;
                        $goodsInfo->goods_shop_price = ($goodsInfo->goods_preferential_price <= 0 ? $extendGoods->goods_extend_price : $goodsInfo->goods_preferential_price);

                        //当未开启优惠价，判断是否有会员价
                        if($goodsInfo->goods_preferential_price <= 0 and $userGroupId > 0) {
                            $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsInfo->goods_id, 'user_group_id'=>$userGroupId, 'adv_spec_tag_id'=>$specTagIdStr));
                            if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $goodsInfo->goods_shop_price = $userGroupPrice->goods_user_group_price;
                        }
                        //获取具体的规格信息
                        $tagArray = $this->getDbshopTable('GoodsTagTable')->listGoodsTag(array('dbshop_goods_tag.tag_id'=>$specTagIdArray));
                        foreach ($tagArray as $tagValue) {
                            $goodsInfo->goods_spec_tag_name .= '<strong>' . $tagValue['tag_group_name'] . '</strong>: ' . $tagValue['tag_name'] . '<br>';
                        }
                        $goodsInfo->goods_spec_tag_id   = $specTagIdStr;
                        $goodsInfo->goods_spec_tag_name = rtrim($goodsInfo->goods_spec_tag_name, '<br>');
                    } else {
                        //当未开启优惠价，判断是否有会员价
                        if($goodsInfo->goods_preferential_price <= 0 and $userGroupId > 0) {
                            $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsInfo->goods_id, 'user_group_id'=>$userGroupId, 'goods_color'=>'', 'goods_size'=>'', 'adv_spec_tag_id'=>''));
                            if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $goodsInfo->goods_shop_price = $userGroupPrice->goods_user_group_price;
                        }
                    }
                } else {//规格普通模式
                    //当颜色和尺寸同时存在情况下，进行检查获取商品库存及颜色和尺寸值，赋值入基础商品中
                    if((isset($colorValue) and !empty($colorValue)) and (isset($sizeValue) and !empty($sizeValue))) {
                        $extendGoods = $this->getDbshopTable('GoodsPriceExtendGoodsTable')->InfoPriceExtendGoods(array('goods_color'=>$colorValue, 'goods_size'=>$sizeValue, 'goods_id'=>$goodsId));
                        if(!$extendGoods) return $this->createJson('error', $this->getDbshopLang()->translate('商品没有您选择的规格存在，无法加入购物车！'));
                        $goodsInfo->goods_stock      = $extendGoods->goods_extend_stock;
                        $goodsInfo->goods_item       = $extendGoods->goods_extend_item;
                        $goodsInfo->goods_shop_price = ($goodsInfo->goods_preferential_price <= 0 ? $extendGoods->goods_extend_price : $goodsInfo->goods_preferential_price);
                        $goodsInfo->goods_color      = $extendGoods->goods_color;
                        $goodsInfo->goods_size       = $extendGoods->goods_size;
                        $goodsInfo->goods_integral_num = $extendGoods->goods_extend_integral;

                        //当未开启优惠价，判断是否有会员价
                        if($goodsInfo->goods_preferential_price <= 0 and $userGroupId > 0) {
                            $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsInfo->goods_id, 'user_group_id'=>$userGroupId, 'goods_color'=>$colorValue, 'goods_size'=>$sizeValue));
                            if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $goodsInfo->goods_shop_price = $userGroupPrice->goods_user_group_price;
                        }

                    } else {//当颜色或者尺寸存在其中一情况下，将其中值赋值入基础商品中
                        $array = array();
                        $array['goods_color'] = isset($colorValue) ? $colorValue : '';
                        $array['goods_size']  = isset($sizeValue) ? $sizeValue : '';
                        $array = array_filter($array);
                        if(!empty($array)) {
                            $item = key($array);
                            $goodsInfo->$item = current($array);
                        }
                        //判断是否有优惠价格存在
                        $goodsInfo->goods_shop_price = ($goodsInfo->goods_preferential_price <= 0 ? $goodsInfo->goods_shop_price : $goodsInfo->goods_preferential_price);
                        //当未开启优惠价，判断是否有会员价
                        if($goodsInfo->goods_preferential_price <= 0 and $userGroupId > 0) {
                            $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsInfo->goods_id, 'user_group_id'=>$userGroupId, 'goods_color'=>'', 'goods_size'=>'', 'adv_spec_tag_id'=>''));
                            if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $goodsInfo->goods_shop_price = $userGroupPrice->goods_user_group_price;
                        }
                    }
                }

                //属性值
                $goodsInfo->goods_color_name = '';
                $goodsInfo->goods_size_name  = '';
                if(isset($goodsInfo->goods_color) and $goodsInfo->goods_color and $goodsInfo->goods_color != 'kongzhi') {
                    $colorInfo       = $this->getDbshopTable('GoodsPriceExtendTable')->infoPriceExtend(array('extend_type'=>'one', 'goods_id'=>$goodsInfo->goods_id));
                    $extendColorInfo = $this->getDbshopTable('GoodsPriceExtendColorTable')->infoPriceExtendColor(array('color_value'=>$goodsInfo->goods_color, 'goods_id'=>$goodsInfo->goods_id));
                    $goodsInfo->goods_color_name = $colorInfo->extend_name . ' : ' . $extendColorInfo->color_info;
                }
                if(isset($goodsInfo->goods_size) and $goodsInfo->goods_size) {
                    $sizeInfo        = $this->getDbshopTable('GoodsPriceExtendTable')->infoPriceExtend(array('extend_type'=>'two', 'goods_id'=>$goodsInfo->goods_id));
                    $extendSizeInfo  = $this->getDbshopTable('GoodsPriceExtendSizeTable')->infoPriceExtendSize(array('size_value'=>$goodsInfo->goods_size, 'goods_id'=>$goodsInfo->goods_id));
                    $goodsInfo->goods_size_name  = $sizeInfo->extend_name . ' : ' . $extendSizeInfo->size_info;
                }

                //判断购物数是否超过库存数
                if($buyNum > $goodsInfo->goods_stock and $goodsInfo->goods_stock_state_open != 1) $msg = $this->getDbshopLang()->translate('购物数量超过商品库存数量，请从新购买！');
                //判断是否有最少购买数量限制
                elseif($goodsInfo->goods_cart_buy_min_num > 0 and $goodsInfo->goods_cart_buy_min_num > $buyNum) $msg = sprintf($this->getDbshopLang()->translate('该商品最少需要购买%s个'),$goodsInfo->goods_cart_buy_min_num);
                //判断是否有最多购买数量限制
                elseif($goodsInfo->goods_cart_buy_max_num > 0 and $goodsInfo->goods_cart_buy_max_num < $buyNum) $msg = sprintf($this->getDbshopLang()->translate('该商品最多购买%s个'),$goodsInfo->goods_cart_buy_max_num);
                //判断在没有数量限制的情况下，是否超过了购买数量
                elseif($goodsInfo->goods_cart_buy_max_num == 0 and $buyNum > 50 and $goodsInfo->goods_cart_buy_min_num == 0) $msg = sprintf($this->getDbshopLang()->translate('该商品最多购买%s个'),50);
                else {
                    $where['goods_id']      = $goodsInfo->goods_id;
                    $where['user_unionid']  = $userUnionid;
                    if(isset($goodsInfo->goods_color) and !empty($goodsInfo->goods_color)) $where['goods_color'] = $goodsInfo->goods_color;
                    if(isset($goodsInfo->goods_size) and !empty($goodsInfo->goods_size)) $where['goods_size'] = $goodsInfo->goods_size;

                    //标识商品唯一性
                    if($goodsInfo->goods_spec_type == 2){//规格高级模式
                        $key = $goodsInfo->goods_id . ((isset($specTagIdStr) and !empty($specTagIdStr)) ? '_' . implode('_', $specTagIdArray) : '');
                    } else {//规格普通模式
                        $key = $goodsInfo->goods_id . ((isset($goodsInfo->goods_color) and !empty($goodsInfo->goods_color)) ? $goodsInfo->goods_color : '') . ((isset($goodsInfo->goods_size) and !empty($goodsInfo->goods_size)) ? $goodsInfo->goods_size : '');
                    }

                    //判断该商品是否已经存在购物车中，如果是存在的，则进行购物数量累加
                    $cartGoodsInfo = $this->getDbshopTable('ApiCartTable')->infoCart($where);
                    if(!empty($cartGoodsInfo)) {
                        $oldBuyNum = $cartGoodsInfo->buy_num;
                        $buyNum    = $oldBuyNum + $buyNum;
                        $msg = $this->editCartGoodsNumCheck($cartGoodsInfo, $buyNum);
                        if(empty($msg)) {//如果msg为空，则说明可以正常处理添加的商品
                            $this->getDbshopTable('ApiCartTable')->editCart(array('buy_num'=>$buyNum), $where);

                            $status = 'success';
                            $msg    = $this->getDbshopLang()->translate('购物车添加成功！');
                        }
                    } else {
                        //获取商品的N个分类信息，主要用于优惠规则中
                        $classIdArray = $this->getDbshopTable('GoodsInClassTable')->listGoodsInClass(array('goods_id'=>$goodsInfo->goods_id));
                        $cartGoods = array(
                            'goods_key'        => $key,
                            'goods_id'         => $goodsInfo->goods_id,
                            'goods_name'       => $goodsInfo->goods_name,
                            'class_id'         => (isset($goodsInfo->main_class_id) and $goodsInfo->main_class_id > 0) ?  $goodsInfo->main_class_id : $classId,
                            'goods_image'      => $this->createDbshopImageUrl($goodsInfo->goods_thumbnail_image),
                            'goods_stock_state'=> $goodsInfo->goods_stock_state_open,//1是开启有货功能，对于库存无限制，0 是使用库存模式
                            'goods_stock'      => $goodsInfo->goods_stock,
                            'buy_num'          => $buyNum,
                            'goods_type'       => $goodsInfo->goods_type,
                            'goods_shop_price' => $goodsInfo->goods_shop_price,
                            'goods_color'      => (isset($goodsInfo->goods_color)      ? $goodsInfo->goods_color      : ''),
                            'goods_size'       => (isset($goodsInfo->goods_size)       ? $goodsInfo->goods_size       : ''),
                            'goods_color_name' => (isset($goodsInfo->goods_color_name) ? $goodsInfo->goods_color_name : ''),
                            'goods_size_name'  => (isset($goodsInfo->goods_size_name)  ? $goodsInfo->goods_size_name  : ''),
                            'goods_adv_tag_id' => (isset($goodsInfo->goods_spec_tag_id) ? $goodsInfo->goods_spec_tag_id : ''),
                            'goods_adv_tag_name'=> (isset($goodsInfo->goods_spec_tag_name)  ? $goodsInfo->goods_spec_tag_name  : ''),
                            'goods_item'       => (isset($goodsInfo->goods_item)       ? $goodsInfo->goods_item  : ''),
                            'goods_weight'     => (isset($goodsInfo->goods_weight)    ? $goodsInfo->goods_weight : 0),
                            'buy_min_num'      => $goodsInfo->goods_cart_buy_min_num,
                            'buy_max_num'      => $goodsInfo->goods_cart_buy_max_num,
                            'integral_num'     => isset($goodsInfo->goods_integral_num) ? ($goodsInfo->goods_integral_num > 0 ? $goodsInfo->goods_integral_num : 0) : 0,
                            'brand_id'         => $goodsInfo->brand_id,//商品品牌
                            'class_id_array'   => $classIdArray,//商品拥有的N个分类id
                            'user_unionid'     => $userUnionid,
                            'user_id'          => isset($this->userData['user_id']) ? $this->userData['user_id'] : 0
                        );
                        $this->getDbshopTable('ApiCartTable')->addCart($cartGoods);

                        $status = 'success';
                        $msg    = $this->getDbshopLang()->translate('购物车添加成功！');
                    }
                }
            }
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 更新购物车商品
     * post
     * goods_key     必填，商品标识唯一性（相对于用户而言）
     * buy_goods_num 必填，变更后的商品数量
     * user_unionid  必填，用户唯一标识，由客户端生成
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return JsonModel
     */
    public function updateCartAction()
    {
        $goodsKey       = isset($this->postData['goods_key']) ? trim($this->postData['goods_key']) : '';
        $userUnionid    = isset($this->postData['user_unionid'])  ? trim($this->postData['user_unionid'])  : '';//用户唯一标识用户设备处生成
        $buyNum         = isset($this->postData['buy_goods_num']) ? (int) $this->postData['buy_goods_num'] : 0;
        $userId         = isset($this->userData['user_id']) ? $this->userData['user_id'] : 0;

        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('购物车修改失败！');
        $array  = array();

        if(!empty($goodsKey) and !empty($userUnionid) and $buyNum > 0) {
            $where['goods_key']     = $goodsKey;
            if($userId <= 0) {
                $where['user_unionid']  = $userUnionid;
            } else {
                $where[] = "(user_unionid='".$userUnionid."' or user_id=".$userId.")";
            }
            $cartGoodsInfo = $this->getDbshopTable('ApiCartTable')->infoCart($where);
            $msg = $this->editCartGoodsNumCheck($cartGoodsInfo, $buyNum);
            if(empty($msg)) {//如果msg为空，则说明可以正常处理添加的商品
                $this->getDbshopTable('ApiCartTable')->editCart(array('buy_num'=>$buyNum), $where);

                $array  = $this->getCartData(
                    array(
                        'user_unionid'      => $cartGoodsInfo->user_unionid,
                        'goods_key'         => $cartGoodsInfo->goods_key,
                        'goods_shop_price'  => $cartGoodsInfo->goods_shop_price,
                    )
                    , $buyNum, 'update');
                $status = 'success';
                $msg    = $this->getDbshopLang()->translate('购物车更新成功！');
            }
        }

        $result = new DbJsonModel(array(
            'status'    => $status,
            'msg'       => $msg,
            'result'    => $array
        ));
        return $result;
    }
    /**
     * 获取购物车信息
     * post
     * user_unionid 必填，用户唯一标识，由客户端生成
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return JsonModel
     */
    public function cartDataAction()
    {
        $userUnionid    = isset($this->postData['user_unionid'])  ? trim($this->postData['user_unionid'])  : '';//用户唯一标识用户设备处生成
        $userId         = isset($this->userData['user_id']) ? $this->userData['user_id'] : 0;

        $array      = array();
        if(!empty($userUnionid)) {
            if($userId <= 0) {
                $where['user_unionid'] = $userUnionid;
            } else {
                $where['user_unionid'] = $userUnionid;
                $where['user_id']      = $userId;
                //$where[] = "user_unionid='".$userUnionid."' or user_id=".$userId;
            }
            $array = $this->getCartData($where);
        }
        return $this->createJsonData($array);
    }
    /**
     * 获取购物车中商品种类的数量
     * post
     * user_unionid 必填，用户唯一标识，由客户端生成
     * user_token   选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return JsonModel
     */
    public function cartGoodsCountAction()
    {
        $userUnionid    = isset($this->postData['user_unionid'])  ? trim($this->postData['user_unionid'])  : '';//用户唯一标识用户设备处生成
        $userId         = isset($this->userData['user_id']) ? $this->userData['user_id'] : 0;

        $cartGoodsCount = 0;
        if(!empty($userUnionid)) {
            if($userId <= 0) {
                $where['user_unionid'] = $userUnionid;
            } else {
                $where[] = "user_unionid='".$userUnionid."' or user_id=".$userId;
            }
            $cartGoodsCount = $this->getDbshopTable('ApiCartTable')->cartGoodsCount($where);
        }

        return $this->createJsonData(array('goods_count'=>$cartGoodsCount));
    }
    /**
     * 删除购物车内的商品
     * post
     * goods_key     必填，商品标识唯一性（相对于用户而言）
     * user_unionid  必填，用户唯一标识，由客户端生成
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return JsonModel
     */
    public function delCartGoodsAction()
    {
        $goodsKey       = isset($this->postData['goods_key']) ? trim($this->postData['goods_key']) : '';
        $userUnionid    = isset($this->postData['user_unionid'])  ? trim($this->postData['user_unionid'])  : '';//用户唯一标识用户设备处生成
        $userId         = isset($this->userData['user_id']) ? $this->userData['user_id'] : 0;

        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('商品删除失败！');
        $array  = array();
        if(!empty($goodsKey) and !empty($userUnionid)) {
            $where['goods_key']     = $goodsKey;
            if($userId <= 0) {
                $where['user_unionid']  = $userUnionid;
            } else {
                $where[] = "(user_unionid='".$userUnionid."' or user_id=".$userId.")";
            }

            $this->getDbshopTable('ApiCartTable')->delCart($where);

            $cartWhere['user_unionid'] = $userUnionid;
            if($userId > 0) $cartWhere['user_id'] = $userId;
            $array  = $this->getCartData($cartWhere);
            $status = 'success';
            $msg    = $this->getDbshopLang()->translate('商品删除成功！');
        }

        $result = new DbJsonModel(array(
            'status'    => $status,
            'msg'       => $msg,
            'result'    => $array
        ));
        return $result;
    }
    /**
     * 清空购物车
     * post
     * user_unionid  必填，用户唯一标识，由客户端生成
     * user_token    选填，用户登录唯一标识,如果用户已经登录，则传递该值
     * @return JsonModel
     */
    public function clearCartAction()
    {
        $userUnionid    = isset($this->postData['user_unionid'])  ? trim($this->postData['user_unionid'])  : '';//用户唯一标识用户设备处生成
        $userId         = isset($this->userData['user_id']) ? $this->userData['user_id'] : 0;

        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('清空购物车失败！');
        if(!empty($userUnionid)) {
            if($userId <= 0) {
                $where['user_unionid'] = $userUnionid;
            } else {
                $where[] = "user_unionid='".$userUnionid."' or user_id=".$userId;
            }
            if($this->getDbshopTable('ApiCartTable')->delCart($where)) {
                $status = 'success';
                $msg    = $this->getDbshopLang()->translate('清空购物车成功！');
            }
        }

        return $this->createJson($status, $msg);
    }
    /*============================================购物车相关============================================*/

    /*============================================用户注册登录相关============================================*/
    /**
     * 用户注册项
     * get
     * @return JsonModel
     */
    public function registerItemAction()
    {
        $array['register_state'] = 'true';
        if($this->getServiceLocator()->get('frontHelper')->getUserIni('user_register_state') == 'false') $array['register_state'] = 'false';

        $array['item'] = array(
            'user_name'         => 'true',
            'user_password'     => 'true',
            'user_com_passwd'   => 'true',
            'user_email'        => 'false',
            'user_phone'        => 'false',
            'phone_captcha'     => 'false'
        );
        //判断注册项中是否开启了邮箱注册
        $userEmailRegisterState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('register_email_state');
        if($userEmailRegisterState == 'true') $array['item']['user_email'] = 'true';
        //判断注册项中是否开启手机号码
        $userPhoneRegisterState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('register_phone_state');
        if($userPhoneRegisterState == 'true') $array['item']['user_phone'] = 'true';
        //判断注册项中是否开启了手机验证码
        $userPhoneCaptchaState = $this->getServiceLocator()->get('frontHelper')->websiteCaptchaState('phone_user_register_captcha');
        if($userPhoneRegisterState == 'true' and $userPhoneCaptchaState == 'true') $array['item']['phone_captcha'] = 'true';

        return $this->createJsonData($array);
    }
    /**
     * 用户扩展注册项
     * @return JsonModel
     */
    public function registerExtendItemAction()
    {
        $fieldArray = $this->getDbshopTable('UserRegExtendFieldTable')->listUserRegExtendField(array('field_state'=>1));
        $array = array();
        if(!empty($fieldArray)) {
            foreach($fieldArray as $fValue) {
                $array[] = array(
                    'input_type' => $fValue['field_type'],
                    'input_title' => $fValue['field_title'],
                    'input_name' => $fValue['field_name'],
                    'input_body' => $fValue['field_radio_checkbox_select'],
                    'field_null' => $fValue['field_null']
                );
            }
        }
        return $this->createJsonData($array);
    }
    /**
     * 会员注册保存
     * post
     * user_unionid  必填，用户唯一标识，由客户端生成
     * @return JsonModel
     */
    public function registerAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('注册失败！');
        //判断是否关闭了注册功能
        if($this->getServiceLocator()->get('frontHelper')->getUserIni('user_register_state') == 'false') {
            $msg = $this->getServiceLocator()->get('frontHelper')->getUserIni('register_close_message');

            return $this->createJson($status, $msg);
        }

        $addUser = array();
        //判断注册用户名是否已经被使用，或者被限制注册
        $checkUserName = $this->checkUserName($this->postData['user_name']);
        if(!$checkUserName['status']) {
            return $this->createJson($status, $checkUserName['message']);
        }
        $addUser['user_name'] = trim($this->postData['user_name']);
        //判断注册项中是否开启了邮箱注册
        $userEmailRegisterState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('register_email_state');
        if($userEmailRegisterState == 'true') {
            $emailValid = new EmailAddress();
            if(!$emailValid->isValid($this->postData['user_email'])) {
                return $this->createJson($status, $this->getDbshopLang()->translate('电子邮件的格式不正确！'));
            }
            $checkUserEmail = $this->checkUserEmail($this->postData['user_email']);
            if(!$checkUserEmail['status']) {
                return $this->createJson($status, $checkUserEmail['message']);
            }
            $addUser['user_email'] = trim($this->postData['user_email']);
        }

        //判断注册项中是否开启手机号码
        $userPhoneRegisterState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('register_phone_state');
        if($userPhoneRegisterState == 'true') {
            $checkUserPhone = $this->checkUserPhone($this->postData['user_phone']);
            if(!$checkUserPhone['status']) {
                return $this->createJson($status, $checkUserPhone['message']);
            }
            $addUser['user_phone'] = trim($this->postData['user_phone']);
        }

        //判断密码与确认密码是否一致
        if(empty($this->postData['user_password']) or empty($this->postData['user_com_passwd']) or $this->postData['user_password'] != $this->postData['user_com_passwd']) {
            return $this->createJson($status, $this->getDbshopLang()->translate('两次输入的密码不同，请重新输入！'));
        }

        //注册验证状态，null 无需验证，email电邮验证，audit人工验证
        $audit = $this->getServiceLocator()->get('frontHelper')->getUserIni('register_audit');
        //是否发送欢迎邮件
        $welcomeEmail = $this->getServiceLocator()->get('frontHelper')->getUserIni('welcomeemail');

        $addUser['user_time']   = time();
        $addUser['group_id']    = $this->getServiceLocator()->get('frontHelper')->getUserIni('default_group_id');
        $addUser['user_state']  = (($audit == 'email' or $audit == 'audit') ? 3 : 1);//默认状态
        $addUser['user_password']= $this->getServiceLocator()->get('frontHelper')->getPasswordStr($this->postData['user_password']);

        /*$this->postData['user_time']     = time();
        $this->postData['group_id']      = $this->getServiceLocator()->get('frontHelper')->getUserIni('default_group_id');
        $this->postData['user_state']    = (($audit == 'email' or $audit == 'audit') ? 3 : 1);//默认状态
        $this->postData['user_password'] = $this->getServiceLocator()->get('frontHelper')->getPasswordStr($this->postData['user_password']);*/

        //会员注册添加
        $addState = $this->getDbshopTable('UserTable')->addUser($addUser);
        if($addState) {
            //事件驱动
            $userArray['user_id']   = $addState;
            $userArray['user_name'] = $addUser['user_name'];
            $this->getEventManager()->trigger('user.register.front.pre', $this, array('values'=>$userArray));
            //初始积分处理
            $userIntegralType = $this->getDbshopTable('UserIntegralTypeTable')->listUserIntegralType(array('e.language'=>$this->getDbshopLang()->getLocale()));
            if(is_array($userIntegralType) and !empty($userIntegralType)) {
                foreach($userIntegralType as $integralTypeValue) {
                    if($integralTypeValue['default_integral_num'] > 0) {
                        $integralLogArray = array();
                        $integralLogArray['user_id']           = $addState;
                        $integralLogArray['user_name']         = $this->postData['user_name'];
                        $integralLogArray['integral_log_info'] = $this->getDbshopLang()->translate('会员注册默认起始积分数：') . $integralTypeValue['default_integral_num'];
                        $integralLogArray['integral_num_log']  = $integralTypeValue['default_integral_num'];
                        $integralLogArray['integral_log_time'] = time();
                        //默认消费积分
                        if($integralTypeValue['integral_type_mark'] == 'integral_type_1') {
                            $this->getDbshopTable('UserTable')->updateUserIntegralNum(array('integral_num_log'=>$integralTypeValue['default_integral_num']), array('user_id'=>$addState));

                            $integralLogArray['integral_type_id'] = 1;
                            $this->getDbshopTable('IntegralLogTable')->addIntegralLog($integralLogArray);
                        }
                        //默认等级积分
                        if($integralTypeValue['integral_type_mark'] == 'integral_type_2') {
                            $this->getDbshopTable('UserTable')->updateUserIntegralNum(array('integral_num_log'=>$integralTypeValue['default_integral_num']), array('user_id'=>$addState), 2);

                            $integralLogArray['integral_type_id'] = 2;
                            $this->getDbshopTable('IntegralLogTable')->addIntegralLog($integralLogArray);
                        }
                    }
                }
            }

            $userGroup = $this->getDbshopTable('UserGroupExtendTable')->infoUserGroupExtend(array('group_id'=>$addUser['group_id'], 'language'=>$this->getDbshopLang()->getLocale()));
            //判断是否对注册成功的会员发送欢迎电邮
            if($welcomeEmail == 'true' and $userEmailRegisterState == 'true') {
                $sourceArray  = array(
                    '{username}',
                    '{shopname}',
                    '{adminemail}',
                    '{time}',
                    '{shopnameurl}'
                );
                $replaceArray = array(
                    $this->postData['user_name'],
                    $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name'),
                    $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_email'),
                    date("Y-m-d H:i", time()),
                    '<a href="'. $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost() . $this->url()->fromRoute('shopfront/default') . '" target="_blank">' . $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name') . '</a>',
                );
                $registerEmail = array(
                    'send_user_name'=> $this->postData['user_name'],
                    'send_mail'     => $this->postData['user_email'],
                    'subject'       => str_replace($sourceArray, $replaceArray, $this->getServiceLocator()->get('frontHelper')->getUserIni('welcome_email_title')),
                    'body'          => nl2br(str_replace($sourceArray, $replaceArray, $this->getServiceLocator()->get('frontHelper')->getUserIni('welcome_email_body'))),
                );
                try {
                    $this->getServiceLocator()->get('shop_send_mail')->toSendMail($registerEmail);
                } catch (\Exception $e) {

                }
            }

            //当验证为电邮验证或者人工验证时进行处理
            $exitMessage = '';
            if($audit == 'email' and $userEmailRegisterState == 'true') {
                $userAuditCode = md5($this->postData['user_name']) . md5(time());
                $auditUrl      = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost() . $this->url()->fromRoute('frontuser/default', array('action'=>'userAudit')) . '?userName=' . urlencode($this->postData['user_name']) . '&auditCode=' . $userAuditCode;
                //将生成的审核码更新到会员表中
                $this->getDbshopTable('UserTable')->updateUser(array('user_audit_code'=>$userAuditCode),array('user_id'=>$addState));
                $auditEmail = array(
                    'send_user_name'=> $this->postData['user_name'],
                    'send_mail'     => $this->postData['user_email'],
                    'subject'       => $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name') . $this->getDbshopLang()->translate('会员注册审核邮件'),
                    'body'          => $this->getDbshopLang()->translate('亲爱的') . $this->postData['user_name'] . $this->getDbshopLang()->translate('您好，感谢您注册我们的会员，请点击会员审核链接进行认证审核 ') . '<a href="'.$auditUrl.'" target="_blank">'
                        . $this->getDbshopLang()->translate('点击审核会员 ') . '</a><br>' . $this->getDbshopLang()->translate('如果您无法点击审核链接，请复制下面的链接地址在浏览器中打开，完成审核 ') . '<br>' . $auditUrl
                );
                try {
                    $this->getServiceLocator()->get('shop_send_mail')->toSendMail($auditEmail);
                    $exitMessage = $this->getDbshopLang()->translate('您的帐户注册成功，需要验证邮件后方可使用，请登录您的邮箱进行验证！');
                } catch (\Exception $e) {
                    $exitMessage = $this->getDbshopLang()->translate('发送验证邮件失败，请联系网站管理员进行处理');
                }
            }
            if($audit == 'audit') $exitMessage = $this->getDbshopLang()->translate('您的帐户注册成功，需要人工审核后才可使用！');
            if($exitMessage != '') {
                return $this->createJson($status, $exitMessage);
            }

            //将会员的登录信息进行序列化
            $user_serialize = array(
                'user_name' =>$this->postData['user_name'],
                'user_id'   =>$addState,
                'user_email'=>(isset($this->postData['user_email']) ? $this->postData['user_email'] : ''),
                'group_id'  =>$addUser['group_id'],
                'user_group_name'=>$userGroup->group_name,
                'user_avatar'=>$this->getServiceLocator()->get('frontHelper')->getUserIni('default_avatar')
            );


            $loginTime     = time();
            $userLoginInfo = array(
                'user_id'       => $addState,
                'user_token'  => md5($addState . $this->postData['user_password'] . $loginTime),
                'user_serialize'=> $user_serialize,
                'user_logintime'=> $loginTime
            );
            //事件驱动
            $this->getEventManager()->trigger('user.register.front.post', $this, array('values'=>$user_serialize));
            //将登录信息存储
            if($this->getDbshopTable('ApiUserLoginTable')->addUserLogin($userLoginInfo)) {
                return $this->createJsonData(array(
                    'user_token' => $userLoginInfo['user_token']
                ));
            }
        }
        return $this->createJson($status, $msg);
    }
    /**
     * 发送手机验证码
     * post
     * user_phone       必填，手机号码
     * phone_captcha    必填，手机验证码，由外部设备自行生成，api不做生成处理
     * @return JsonModel
     */
    public function phoneCaptchaAction()
    {
        $userPhone      = isset($this->postData['user_phone']) ? $this->postData['user_phone'] : '';
        $phoneCaptcha   = isset($this->postData['phone_captcha']) ? $this->postData['phone_captcha'] : '';

        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('验证码发送失败！');

        if(empty($userPhone) or !is_numeric($userPhone)) {
            return $this->createJson($status, $this->getDbshopLang()->translate('不是正确的手机号码!'));
        }
        $phoneState = $this->getServiceLocator()->get('frontHelper')->checkPhoneNum($userPhone);//preg_match('#^13[\d]{9}$|^14[\d]{9}$|^15[\d]{9}$|^17[\d]{9}$|^18[\d]{9}$#', $userPhone) ? 'true' : 'false';
        if($phoneState == 'false') {
            return $this->createJson($status, $this->getDbshopLang()->translate('不是正确的手机号码!'));
        }

        try {
            $this->getServiceLocator()->get('shop_send_sms')->toSendSms(
                array(
                    'captcha'           => $phoneCaptcha,
                    'patcheashopname'   => $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name')
                ),
                $userPhone,
                'alidayu_phone_captcha_template_id'
            );
            $status = 'success';
            $msg    = $this->getDbshopLang()->translate('验证码发送成功！');
        } catch(\Exception $e) {
            $msg = $this->getDbshopLang()->translate('系统未开启手机验证功能!');
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 获取会员当前的登录状态
     * post
     * user_token   必填，用户登录唯一标识
     * @return JsonModel
     */
    public function loginStateAction()
    {
        $userId = isset($this->userData['user_id'])  ? $this->userData['user_id']  : 0;//用户id
        if($userId > 0) {
            return $this->createJson('success', $this->getDbshopLang()->translate('该用户目前处于登录状态！'));
        }
        return $this->createJson('error', $this->getDbshopLang()->translate('该用户目前处于退出状态！'));
    }
    /**
     * 登录项，可支持的登录项
     * get
     * @return JsonModel
     */
    public function loginItemAction()
    {
        $array['user_name'] = array(
            'user_name'     => 'true',
            'user_email'    => 'false',
            'user_phone'    => 'false'
        );
        $array['user_password'] = 'true';

        //判断登录项中是否开启了邮箱登录
        $userEmailLoginState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('login_email_state');
        if($userEmailLoginState == 'true') $array['user_name']['user_email'] = 'true';
        //判断登录项中是否开启手机号码登录
        $userPhoneLoginState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('login_phone_state');
        if($userPhoneLoginState == 'true') $array['user_name']['user_phone'] = 'true';

        return $this->createJsonData($array);
    }
    /**
     * 会员登录
     * post
     * user_name        必填  用户名称
     * user_password    必填  用户密码
     * user_unionid     必填，用户唯一标识，由客户端生成
     * @return JsonModel|DbJsonModel
     */
    public function loginAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('您的密码错误，或者您的账号不存在！');
        //判断登录项中是否开启了邮箱登录
        $userEmailLoginState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('login_email_state');
        //判断登录项中是否开启手机号码登录
        $userPhoneLoginState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('login_phone_state');

        if(empty(trim($this->postData['user_name']))) return $this->createJson($status, $this->getDbshopLang()->translate('登录账户信息不能为空！'));

        $filter = new HtmlEntities();
        $userNameWhere = '(user_name="'.$filter->filter($this->postData['user_name']).'"';
        if($userEmailLoginState == 'true') $userNameWhere .= ' or user_email="'.$filter->filter($this->postData['user_name']).'"';    //开启邮箱登录
        if($userPhoneLoginState == 'true') $userNameWhere .= ' or user_phone="'.$filter->filter($this->postData['user_name']).'"';     //开启手机号码登录
        $userNameWhere .= ')';

        $userArray['user_password'] = $this->getServiceLocator()->get('frontHelper')->getPasswordStr($this->postData['user_password']);
        $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_password'=>$userArray['user_password'], $userNameWhere));
        if($userInfo
            and $userInfo->user_password == $userArray['user_password']
            and in_array($this->postData['user_name'], array($userInfo->user_name, $userInfo->user_email, $userInfo->user_phone))) {
            //当会员状态处于2（关闭）3（待审核）时，不进行登录操作
            $exitMessage = '';
            if($userInfo->user_state == 2) $exitMessage = $this->getDbshopLang()->translate('您的帐户处于关闭状态！');
            if($userInfo->user_state == 3) $exitMessage = $this->getDbshopLang()->translate('您的帐户处于待审核状态！');
            if($exitMessage != '') {
                return $this->createJson($status, $exitMessage);
            }
            //根据等级积分判读，当前登录用户是否需要调整等级
            $groupId = $this->getDbshopTable('UserGroupTable')->checkUserGroup(array('group_id'=>$userInfo->group_id, 'integral_num'=>$userInfo->integral_type_2_num));
            if($groupId) {
                $this->getDbshopTable('UserTable')->updateUser(array('group_id'=>$groupId), array('user_id'=>$userInfo->user_id));
                $userInfo->group_id = $groupId;
            }
            $userGroup = $this->getDbshopTable('UserGroupExtendTable')->infoUserGroupExtend(array('group_id'=>$userInfo->group_id,'language'=>$this->getDbshopLang()->getLocale()));

            $user_serialize = array(
                'user_name'      => $userInfo->user_name,
                'user_id'        => $userInfo->user_id,
                'user_email'     => $userInfo->user_email,
                'user_phone'     => $userInfo->user_phone,
                'group_id'       => $userInfo->group_id,
                'user_group_name'=> $userGroup->group_name,
                'user_avatar'    => (!empty($userInfo->user_avatar) ? $this->createDbshopImageUrl($userInfo->user_avatar) : $this->createDbshopImageUrl($this->getServiceLocator()->get('frontHelper')->getUserIni('default_avatar')))
            );
            $loginTime     = time();
            $userLoginInfo = array(
                'user_id'       => $userInfo->user_id,
                'user_token'    => md5($userInfo->user_id . $this->postData['user_password'] . $loginTime),
                'user_serialize'=> $user_serialize,
                'user_logintime'=> $loginTime
            );
            //事件驱动
            $this->getEventManager()->trigger('user.login.front.post', $this, array('values'=>$user_serialize));
            //将登录信息存储
            $this->getDbshopTable('ApiUserLoginTable')->delUserLogin(array('user_id'=>$userInfo->user_id));//先移除掉之前的登录信息（如果有的话）
            if($this->getDbshopTable('ApiUserLoginTable')->addUserLogin($userLoginInfo)) {
                return $this->createJsonData(array(
                    'user_name'     => $user_serialize['user_name'],
                    'nick_name'     => $user_serialize['user_name'],
                    'user_avatar'   => $user_serialize['user_avatar'],
                    'user_token'    => $userLoginInfo['user_token'],
                    'user_unionid'  => md5($user_serialize['user_name'])
                ));
            }
        }
        return $this->createJson($status, $msg);
    }
    /**
     * 小程序微信登陆
     * post
     * user_name    必填，会员名称
     * user_avatar  必填，会员头像
     * user_sex     必填，会员性别
     * code         必填，小程序那边传过来的code
     *
     * @return DbJsonModel
     */
    public function loginWeixinAction()
    {
        $userName   = isset($this->postData['user_name'])   ? trim($this->filterEmoji($this->postData['user_name']))    : '';
        $userAvatar = isset($this->postData['user_avatar']) ? trim($this->postData['user_avatar'])  : '';
        $userSex    = isset($this->postData['user_sex'])    ? trim($this->postData['user_sex'])     : '';
        $code       = isset($this->postData['code'])        ? trim($this->postData['code'])         : '';

        $appId = apiConfig::WX_APP_ID;
        $secret= apiConfig::WX_APP_SECRET;
        $apiUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appId.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $user_serialize = array();

        $info = json_decode(file_get_contents($apiUrl));
        if(isset($info->openid) or isset($info->unionid)) {

            $openid = $info->openid;
            $unionId= $info->unionid;

            $where  = '(dbshop_other_login.login_type="Weixin" or dbshop_other_login.login_type="Weixinphone")';
            $userInfo = $this->getDbshopTable('OtherLoginTable')->infoOtherLogin(array('dbshop_other_login.open_id'=>$openid, $where));
            if(!empty($unionId) and $unionId != $openid and empty($userInfo))  $userInfo = $this->getDbshopTable('OtherLoginTable')->infoOtherLogin(array('dbshop_other_login.open_id'=>$unionId, $where));
            if($userInfo) {
                //如果openid与unionid不一样，更新成unioid，这里主要是对微信的处理
                if(!empty($info->unionid) and $userInfo->open_id != $info->unionid) {
                    $this->getDbshopTable('OtherLoginTable')->updateOtherLogin(array('open_id'=>$info->unionid), array('open_id'=>$userInfo->open_id));
                }
                $userGroup = $this->getDbshopTable('UserGroupExtendTable')->infoUserGroupExtend(array('group_id'=>$userInfo->group_id,'language'=>$this->getDbshopLang()->getLocale()));

                $user_serialize = array(
                    'user_name'      => $userInfo->user_name,
                    'user_id'        => $userInfo->user_id,
                    'user_email'     => $userInfo->user_email,
                    'user_phone'     => $userInfo->user_phone,
                    'group_id'       => $userInfo->group_id,
                    'user_group_name'=> $userGroup->group_name,
                    'user_avatar'    => (!empty($userInfo->user_avatar) ? $userInfo->user_avatar : $this->getServiceLocator()->get('frontHelper')->getUserIni('default_avatar'))
                );
                $loginTime     = time();
                $userLoginInfo = array(
                    'user_id'       => $userInfo->user_id,
                    'user_token'    => md5($userInfo->user_id . $userInfo->user_password . $loginTime),
                    'user_serialize'=> $user_serialize,
                    'user_logintime'=> $loginTime
                );
                //事件驱动
                $this->getEventManager()->trigger('user.login.front.post', $this, array('values'=>$user_serialize));
                //将登录信息存储
                $this->getDbshopTable('ApiUserLoginTable')->delUserLogin(array('user_id'=>$userInfo->user_id));//先移除掉之前的登录信息（如果有的话）

            } else {
                if(!empty($unionId) and $unionId != $openid) $openid = $unionId;

                $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_name'=>$userName));

                $userArray = array(
                    'user_name'     => !empty($userInfo) ? $userName . rand(1, 999) : $userName,
                    'user_avatar'   => $userAvatar,
                    'user_sex'      => $userSex == 0 ? 3 : $userSex,
                    'group_id'      => $this->getServiceLocator()->get('frontHelper')->getUserIni('default_group_id'),
                    'user_state'    => 1,
                    'user_time'     => time(),
                    'user_password' => $this->getServiceLocator()->get('frontHelper')->getPasswordStr($openid)
                );
                $addState = $this->getDbshopTable('UserTable')->addUser($userArray);
                if($addState) {
                    $otherLoginArray = array(
                        'user_id'       => $addState,
                        'open_id'       => $openid,
                        'ol_add_time'   => time(),
                        'login_type'    => 'Weixin'
                    );
                    $this->getDbshopTable('OtherLoginTable')->addOtherLogin($otherLoginArray);

                    //事件驱动
                    $userArray['user_id'] = $addState;
                    $this->getEventManager()->trigger('user.register.front.pre', $this, array('values'=>$userArray));
                    //初始积分处理
                    $userIntegralType = $this->getDbshopTable('UserIntegralTypeTable')->listUserIntegralType(array('e.language'=>$this->getDbshopLang()->getLocale()));
                    if(is_array($userIntegralType) and !empty($userIntegralType)) {
                        foreach($userIntegralType as $integralTypeValue) {
                            if($integralTypeValue['default_integral_num'] > 0) {
                                $integralLogArray = array();
                                $integralLogArray['user_id']           = $addState;
                                $integralLogArray['user_name']         = $userName;
                                $integralLogArray['integral_log_info'] = $this->getDbshopLang()->translate('会员注册默认起始积分数：') . $integralTypeValue['default_integral_num'];
                                $integralLogArray['integral_num_log']  = $integralTypeValue['default_integral_num'];
                                $integralLogArray['integral_log_time'] = time();
                                //默认消费积分
                                if($integralTypeValue['integral_type_mark'] == 'integral_type_1') {
                                    $this->getDbshopTable('UserTable')->updateUserIntegralNum(array('integral_num_log'=>$integralTypeValue['default_integral_num']), array('user_id'=>$addState));

                                    $integralLogArray['integral_type_id'] = 1;
                                    $this->getDbshopTable('IntegralLogTable')->addIntegralLog($integralLogArray);
                                }
                                //默认等级积分
                                if($integralTypeValue['integral_type_mark'] == 'integral_type_2') {
                                    $this->getDbshopTable('UserTable')->updateUserIntegralNum(array('integral_num_log'=>$integralTypeValue['default_integral_num']), array('user_id'=>$addState), 2);

                                    $integralLogArray['integral_type_id'] = 2;
                                    $this->getDbshopTable('IntegralLogTable')->addIntegralLog($integralLogArray);
                                }
                            }
                        }
                    }

                    $userGroup = $this->getDbshopTable('UserGroupExtendTable')->infoUserGroupExtend(array('group_id'=>$userArray['group_id'], 'language'=>$this->getDbshopLang()->getLocale()));

                    //将会员的登录信息进行序列化
                    $user_serialize = array(
                        'user_name' =>$userArray['user_name'],
                        'user_id'   =>$addState,
                        'user_email'=>'',
                        'group_id'  =>$userArray['group_id'],
                        'user_group_name'=>$userGroup->group_name,
                        'user_avatar'=>$userAvatar
                    );
                    $loginTime     = time();
                    $userLoginInfo = array(
                        'user_id'       => $addState,
                        'user_token'    => md5($addState . $userArray['user_password'] . $loginTime),
                        'user_serialize'=> $user_serialize,
                        'user_logintime'=> $loginTime
                    );
                    //事件驱动
                    $this->getEventManager()->trigger('user.register.front.post', $this, array('values'=>$user_serialize));
                }

            }
        }
        if(!empty($user_serialize)) {
            //将登录信息存储
            if($this->getDbshopTable('ApiUserLoginTable')->addUserLogin($userLoginInfo)) {
                return $this->createJsonData(array(
                    'user_name'     => $user_serialize['user_name'],
                    'nick_name'     => $userName,
                    'user_avatar'   => $userAvatar,
                    'user_token'    => $userLoginInfo['user_token'],
                    'user_unionid'  => md5($user_serialize['user_name'])
                ));
            }
        }
        return $this->createJsonData($user_serialize, 'error');
    }
    /**
     * 会员退出处理
     * post
     * user_token   必填，用户登录唯一标识
     * @return JsonModel
     */
    public function loginOutAction()
    {
        $userToken = isset($this->postData['user_token'])  ? trim($this->postData['user_token'])  : '';//用户登录唯一标识
        if(!empty($userToken)) {
            $this->getDbshopTable('ApiUserLoginTable')->delUserLogin(array('user_token'=>$userToken));
        }
        $result = new DbJsonModel(array(
            'status'    => 'success',
            'msg'       => $this->getDbshopLang()->translate('退出成功！')
        ));
        return $result;
    }
    /**
     * 注册协议
     * get
     * @return JsonModel
     */
    public function agreementAction()
    {
        $array['body'] = nl2br($this->getServiceLocator()->get('frontHelper')->getUserIni('user_register_body'));

        return $this->createJsonData($array);
    }
    /**
     * 找回密码
     * post
     * user_name    必填，用户名称
     * user_email   必填，用户电子邮箱
     * @return JsonModel
     */
    public function forgotpasswdAction()
    {
        $status = 'error';

        $userName   = isset($this->postData['user_name'])   ? trim($this->postData['user_name']) : '';
        $userEmail  = isset($this->postData['user_email'])  ? trim($this->postData['user_email']) : '';

        $userInfo  = $this->getDbshopTable('UserTable')->infoUser(array('user_name'=>$userName, 'user_email'=>$userEmail));
        if(isset($userInfo->user_name) and $userInfo->user_name != '') {
            //生成唯一码及url
            $editCode = md5($userInfo->user_name . $userInfo->user_email) . md5(time());
            $editUrl = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost() . $this->url()->fromRoute('frontuser/default', array('action' => 'forgotpasswdedit')) . '?editcode=' . $editCode;
            //发送的邮件内容
            $forgotEmail = array(
                'send_user_name' => $userInfo->user_name,
                'send_mail' => $userInfo->user_email,
                'subject' => $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name') . $this->getDbshopLang()->translate('会员密码修改'),
                'body' => $this->getDbshopLang()->translate('亲爱的') . $userInfo->user_name . '<br>' . $this->getDbshopLang()->translate('您好，请点击下面的链接进行密码修改') . '<a href="' . $editUrl . '" target="_blank">'
                    . $this->getDbshopLang()->translate('点击修改密码 ') . '</a><br>' . $this->getDbshopLang()->translate('如果您无法点击修改链接，请复制下面的链接地址在浏览器中打开，完成密码修改 ') . '<br>' . $editUrl
            );
            try {
                $this->getServiceLocator()->get('shop_send_mail')->toSendMail($forgotEmail);
                $this->getDbshopTable('UserTable')->updateUser(array('user_forgot_passwd_code' => $editCode), array('user_id' => $userInfo->user_id));

                $status = 'success';
                $msg = sprintf($this->getDbshopLang()->translate('已经向您的邮箱 %s 发送了一封邮件，请根据邮件内容完成新密码设定'), $userInfo->user_email);
            } catch (\Exception $e) {
                $msg = $this->getDbshopLang()->translate('无法向您的邮箱发送邮件，请联系管理员处理！');
            }
        } else {
            $msg = $this->getDbshopLang()->translate('您输入的信息错误，没有匹配的会员信息！');
        }

        return $this->createJson($status, $msg);
    }
    /*============================================用户注册登录相关============================================*/

    /*============================================订单提交相关============================================*/
    /**
     * 获取配送地址信息
     * post
     * user_token   必填，用户登录唯一标识
     * address_id   必填，收货地址id
     * @return JsonModel
     */
    public function addressInfoAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('无该配送信息！');

        $addressInfo = array();

        $userId = isset($this->userData['user_id'])  ? $this->userData['user_id']  : '';//用户id
        $addressId = isset($this->postData['address_id']) ? intval($this->postData['address_id']) : 0;
        if($userId > 0 && $addressId > 0) {
            $addressInfo = $this->getDbshopTable('UserAddressTable')->infoAddress(array('user_id'=>$userId, 'address_id'=>$addressId));
            if(!empty($addressInfo)) $status = 'success';
        }

        return $this->createJsonData($addressInfo, $status);
    }
    /**
     * 获取配送地址列表
     * post
     * user_token 必填，用户登录唯一标识
     * @return JsonModel
     */
    public function addressListAction()
    {
        $userId         = isset($this->userData['user_id'])  ? $this->userData['user_id']  : '';//用户id
        $addressList    = array();
        if($userId > 0) {
            $addressList = $this->getDbshopTable('UserAddressTable')->listAddress(array('user_id'=>$userId));
        }

        return $this->createJsonData($addressList);
    }
    /**
     * 添加或更新配送地址
     * post
     * user_token   必填，用户登录唯一标识
     * address_id   非必填，为空时添加配送地址，不为空时更新配送地址
     * true_name    必填，收货人姓名
     * region_id    必填，最后选中的地区id，比如 设置的 北京市 朝阳区 那么region_id就是朝阳区的id
     * region_value 必填，选中的所有地区的名称，比如 设置的 北京市 朝阳区 那么region_value就是 北京市 朝阳区
     * address      必填，详细地址
     * zip_code     必填，邮政编码
     * mod_phone    必填，手机号码
     * tel_area_code非必填，座机号码的区号
     * tel_phone    非必填，座机号码
     * tel_ext      非必填，座机分机号
     * addr_default 非必填，是否为默认配送地址，1为默认配送地址
     * @return JsonModel
     */
    public function saveAddressAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('配送地址处理失败！');

        $userId = isset($this->userData['user_id'])  ? $this->userData['user_id']  : 0;//用户id
        if($userId > 0) {
            $addressId = isset($this->postData['address_id']) ? intval($this->postData['address_id']) : 0;
            if($addressId == 0) {
                $this->postData['user_id'] = $userId;
                $this->getDbshopTable('UserAddressTable')->addAddress($this->postData);
                $msg = $this->getDbshopLang()->translate('配送地址添加成功！');
            } else {
                $this->getDbshopTable('UserAddressTable')->updateAddress($this->postData, array('address_id'=>$addressId, 'user_id'=>$userId));
                $msg = $this->getDbshopLang()->translate('配送地址更新成功！');
            }
            $status = 'success';
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 删除配送地址
     * post
     * user_token 必填，用户登录唯一标识
     * address_id 必填，配送地址id
     * @return JsonModel
     */
    public function delAddressAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('配送地址删除失败！');

        $userId     = isset($this->userData['user_id'])  ? $this->userData['user_id']  : 0;             //用户id
        $addressId  = isset($this->postData['address_id']) ? intval($this->postData['address_id']) : 0; //配送地址id
        if($userId > 0 and $addressId > 0) {
            if($this->getDbshopTable('UserAddressTable')->delAddress(array('address_id'=>$addressId , 'user_id'=>$userId))) {
                $status = 'success';
                $msg    = $this->getDbshopLang()->translate('配送地址删除成功！');
            }
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 获取地区列表
     * post
     * region_top_id 必填，上一级的地区id，0是获取顶级地区信息
     * @return DbJsonModel
     */
    public function regionAction()
    {
        $regionTopId = isset($this->postData['region_top_id']) ? intval($this->postData['region_top_id']) : 0;
        $regionList  = $this->getDbshopTable('RegionTable')->listRegion(array('dbshop_region.region_top_id'=>$regionTopId,'e.language'=>$this->getDbshopLang()->getLocale()));
        if(!empty($regionList)) {
            $regionArray = $regionList;
        } else $regionArray = array();

        return $this->createJsonData($regionArray);
    }
    /**
     * 积分转换金额
     * post
     * user_token           必填，用户登录唯一标识
     * integral_num         必填，积分数
     * cart_integral_num    必填，本次购物可以使用多少积分购买
     */
    public function integralConvertMoneyAction()
    {
        $userId     = isset($this->userData['user_id'])     ? $this->userData['user_id']  : 0;//用户id
        $integralNum= isset($this->postData['integral_num'])  ? (int) $this->postData['integral_num']  : 0;
        $cartIntegralNum= isset($this->postData['cart_integral_num'])  ? (int) $this->postData['cart_integral_num']  : 0;

        $array = array('money'=>0);
        if($userId > 0 and $integralNum > 0 and $cartIntegralNum > 0) {
            $userIntegralInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$userId));
            if($userIntegralInfo->user_integral_num < $integralNum or $integralNum > $cartIntegralNum) $integralNum = 0;
            else {
                $integralInfo       = $this->getDbshopTable('UserIntegralTypeTable')->userIntegarlTypeOneInfo(array('integral_type_id'=>1));
                $integralBuyPrice   = $integralInfo->integral_currency_con / 100 * $integralNum;
                $array['money'] = $integralBuyPrice;
                //print_r($array);exit;
            }
        }
        return $this->createJsonData($array);
    }
    /**
     * 订单确认
     * post
     * user_unionid 必填，用户唯一标识，由客户端生成
     * address_id   必填，已经选择的配送地址id
     * user_token 必填，用户登录唯一标识
     * @return JsonModel
     */
    public function stepAction()
    {
        $userId     = isset($this->userData['user_id'])     ? $this->userData['user_id']  : 0;//用户id
        $addressId  = isset($this->postData['address_id'])  ? $this->postData['address_id']  : 0;//配送地址id
        $userUnionid= isset($this->postData['user_unionid'])  ? $this->postData['user_unionid']  : '';

        $array      = array();

        if($userId > 0 and !empty($userUnionid)) {
            //配送地址列表
            $addressList = $this->getDbshopTable('UserAddressTable')->listAddress(array('user_id'=>$userId));
            $array['addressList'] = array();
            if(!empty($addressList)) {
                foreach($addressList as $addreValue) {
                    $array['addressList'][$addreValue['address_id']] = $addreValue;
                    //当时默认地址，且系统没有传过来指定地址id时，设置
                    if($addreValue['addr_default'] == 1 and $addressId <= 0) $addressId = $addreValue['address_id'];
                }
            }
            //获取默认选中地址详细信息
            $array['default_address'] = array();
            if($addressId > 0) $array['default_address'] = $array['addressList'][$addressId];
            else {
                if(!empty($array['addressList'])) {
                    $addressId = $addressList[0]['address_id'];
                    $array['default_address'] = $addressList[0];
                }
            }
            //进行一次购物车商品的归属设置
            $this->getDbshopTable('ApiCartTable')->editCart(array('user_unionid'=>$userUnionid), array("user_id=".$userId." and user_unionid IS NULL"));
            $this->getDbshopTable('ApiCartTable')->editCart(array('user_id'=>$userId), array("user_unionid='".$userUnionid."' and user_id=0"));
            //购物车商品信息矫正，主要矫正的是商品价格，防止在商品被放入购物车后，后台管理员人员进行改价处理
            $this->checkCartGoodsPrice($userUnionid);
            //购物车内的信息
            $array['cart'] = $this->getCartData(array('user_unionid'=>$userUnionid));
            if(empty($array['cart'])) return $this->createJson('error', $this->getDbshopLang()->translate('购物车内无商品信息！'));
            //商品总重量
            $array['total_weight'] = $array['cart']['cart_weight'];
            //购物车内商品总金额
            $cartTotalPrice = $array['cart']['cart_price'];

            if($addressId > 0 and !empty($array['default_address'])) {
                //获取配送地址对应的地区
                $addressInfo  = $this->getDbshopTable('UserAddressTable')->infoAddress(array('address_id'=>$addressId, 'user_id'=>$userId));
                if(!$addressInfo) return $this->createJson('error', $this->getDbshopLang()->translate('配送地址不匹配！'));

                $regionInfo   = $this->getDbshopTable('RegionTable')->infoRegion(array('dbshop_region.region_id'=>$addressInfo['region_id']));
                $regionIdArray= explode(',', $regionInfo['region_path']);
                //获取配送方式信息
                $configReader = new \Zend\Config\Reader\Ini();
                $cashOnDelivery= '';
                $expressArray = $this->getDbshopTable('ExpressTable')->listExpress(array('express_state'=>1));
                if(is_array($expressArray) and !empty($expressArray)) {
                    $expressConfigFilePath = DBSHOP_PATH . '/data/moduledata/Express/';
                    $i = 0;
                    $totalWeight = $array['total_weight'] * 1000;//将千克换算成克
                    foreach ($expressArray as $value) {//循环读取配送方式的设置文件
                        $expressExist = false;
                        if(file_exists($expressConfigFilePath . $value['express_id'] . '.ini')) {
                            $expressConfig = $configReader->fromFile($expressConfigFilePath . $value['express_id'] . '.ini');
                            if($expressConfig['express_set'] == 'T') {//当为统一设置时进行的处理
                                $value['express_price'] = $this->getServiceLocator()->get('shop_express')->calculateCost(trim($expressConfig['express_price']), $totalWeight, $cartTotalPrice);
                                $expressExist = true;
                            } else {//当为个性化设置的时候，进行地区匹配
                                $value['express_price'] = 0;
                                foreach ($expressConfig['express_price'] as $price_value) {
                                    $price_value['price'] = $this->getServiceLocator()->get('shop_express')->calculateCost(trim($price_value['price']), $totalWeight, $cartTotalPrice);
                                    foreach ($regionIdArray as $regionId) {//循环查询，当前配送地址的地区id及其上级地区，是否在配送地区中有所体现，这里的foreach有点多了，待优化
                                        if(in_array($regionId, $price_value['area_id'])) {
                                            $value['express_price'] = ($value['express_price'] > 0 and $value['express_price'] < $price_value['price']) ? $value['express_price'] : $price_value['price'];
                                            $expressExist = true;
                                        }
                                    }
                                }
                            }
                            //这是获取可以货到付款的配送方式的id字符串相连
                            if($value['cash_on_delivery'] == 1) $cashOnDelivery .= "'".$value['express_id'] . "',";
                        }
                        if($expressExist) {
                            $value['express_price'] = $this->getServiceLocator()->get('frontHelper')->shopPrice($value['express_price']);

                            $array['shippingList'][$i] = $value;
                            $i++;
                        }
                    }
                }
                if(!empty($array['shippingList'])) $array['shippingList'][0]['selected'] = 1;
                //可以货到付款的配送方式的id字符串相连
                $array['cash_on_delivery_str'] = (!empty($cashOnDelivery) ? substr($cashOnDelivery, 0, -1) : '');
            }

            /*----------------------支付方式----------------------*/
            $paymentArray = array();
            $filePath      = DBSHOP_PATH . '/data/moduledata/Payment/';
            if(is_dir($filePath)) {
                $dh = opendir($filePath);
                while (false !== ($fileName = readdir($dh))) {
                    if($fileName != '.' and $fileName != '..' and stripos($fileName, '.php') !== false and $fileName != '.DS_Store') {
                        $paymentInfo = include($filePath . $fileName);

                        $paymentInfo['payment_logo']['content'] = $this->createDbshopImageUrl($paymentInfo['payment_logo']['content'], false);
                        //判断是否显示在当前平台
                        if(isset($paymentInfo['payment_show']['checked']) and !empty($paymentInfo['payment_show']['checked'])) {
                            $showArray = is_array($paymentInfo['payment_show']['checked']) ? $paymentInfo['payment_show']['checked'] : array($paymentInfo['payment_show']['checked']);
                            if(!in_array('pc', $showArray) and !in_array('all', $showArray)) continue;
                        } else continue;

                        //判断是否符合当前的货币要求
                        $currencyState = false;
                        if(isset($paymentInfo['payment_currency']['checked']) and !empty($paymentInfo['payment_currency']['checked'])) {
                            $currencyArray = is_array($paymentInfo['payment_currency']['checked']) ? $paymentInfo['payment_currency']['checked'] : array($paymentInfo['payment_currency']['checked']);
                            $currencyState = in_array($this->getServiceLocator()->get('frontHelper')->getFrontDefaultCurrency(), $currencyArray) ? true : false;
                        } elseif (in_array($paymentInfo['editaction'], array('xxzf', 'hdfk'))) {//线下支付或者货到付款时，不进行货币判断
                            $currencyState = true;
                        }

                        if($paymentInfo['payment_state']['checked'] == 1 and $currencyState) {
                            $paymentInfo['payment_fee']['content'] = ((strpos($paymentInfo['payment_fee']['content'], '%') !== false) ? round($cartTotalPrice * str_replace('%', '', $paymentInfo['payment_fee']['content'])/100, 2) : round($this->getServiceLocator()->get('frontHelper')->shopPrice($paymentInfo['payment_fee']['content']), 2));
                            $paymentArray[] = $paymentInfo;
                        }
                    }
                }
            }
            //排序操作
            usort($paymentArray, function ($a, $b) {
                if($a['payment_sort']['content'] == $b['payment_sort']['content']) {
                    return 0;
                }
                return ($a['payment_sort']['content'] < $b['payment_sort']['content']) ? -1 : 1;
            });
            $array['payment'] = $paymentArray;
            if(!empty($array['payment'])) $array['payment'][0]['selected'] = 1;

            //订单金额
            $array['order_total'] = $array['shippingList'][0]['express_price'] + $array['payment'][0]['payment_fee']['content'] + $array['cart']['cart_price'] - $array['cart']['discount']['discount_cost'];
            //会员消费积分
            $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$userId));
            $array['userIntegralNum'] = $userInfo->user_integral_num;
            //获取积分转换比例
            $integralInfo = $this->getDbshopTable('UserIntegralTypeTable')->userIntegarlTypeOneInfo(array('integral_type_id'=>1));
            $currencyRate = $this->getServiceLocator()->get('frontHelper')->shopPriceRate();
            $array['integralCurrencyCon'] = $integralInfo->integral_currency_con / 100 * $currencyRate;
            //检查是否有可用的优惠券
            $userCouponList = CouponRuleService::couponUseRule(array('cartGoods'=>$array['cart']['cart_goods'], 'user_id'=>$userId), $this);
            if($userCouponList) $array['use_coupon'] = $userCouponList;
        }

        return $this->createJsonData($array);
    }
    /**
     * 订单提交处理
     * post
     * user_unionid 必填，用户唯一标识，由客户端生成
     * address_id   必填，已经选择的配送地址id
     * user_token   必填，用户登录唯一标识
     * payment_code 必填，支付方式标识码
     * express_id   必填，配送方式id
     *
     * integral_buy_num 非必填，用户使用的消费积分（只有购物车商品可以使用积分时，才会需要）
     * order_message    非必填，订单留言信息
     * invoice_title    非必填，发票抬头（文字形式）
     * invoice_content  非必填，发票内容（文字形式）
     * shipping_time    非必填，送货时间（文字形式）
     * coupon_id        非必填，当有可用优惠券，且选择了优惠券传过来的id值
     *
     * @return JsonModel
     */
    public function cartSubmitAction()
    {
        //必填
        $userId     = isset($this->userData['user_id'])       ? intval($this->userData['user_id'])      : 0;//用户id
        $addressId  = isset($this->postData['address_id'])    ? intval($this->postData['address_id'])   : 0;//配送地址id
        $userUnionid= isset($this->postData['user_unionid'])  ? $this->postData['user_unionid'] : '';
        $paymentCode= isset($this->postData['payment_code'])  ? basename($this->postData['payment_code']) : '';
        $expressId  = isset($this->postData['express_id'])    ? intval($this->postData['express_id'])   : 0;

        //非必填
        $integralBuyNum     = isset($this->postData['integral_buy_num'])    ? intval($this->postData['integral_buy_num'])   : 0;
        $orderMessage       = isset($this->postData['order_message'])       ? trim($this->postData['order_message'])   : '';
        $invoiceTitle       = isset($this->postData['invoice_title'])       ? trim($this->postData['invoice_title'])   : '';
        $invoiceContent     = isset($this->postData['invoice_content'])     ? trim($this->postData['invoice_content']) : '';
        $shippingTime       = isset($this->postData['shipping_time'])     ? trim($this->postData['shipping_time']) : '';
        $couponId           = isset($this->postData['coupon_id'])           ? intval($this->postData['coupon_id']) : 0;

        $orderJsonArray = array();

        if($userId > 0 and $addressId > 0 and !empty($userUnionid) and !empty($paymentCode) and $expressId > 0) {
            //购物车内的信息
            $cart = $this->getCartData(array('user_unionid'=>$userUnionid));
            if(empty($cart)) return $this->createJson('error', $this->getDbshopLang()->translate('购物车内无商品信息！'));
            //购物车内商品总价
            $cartTotalPrice = $cart['cart_price'];
            //获取支付方式信息
            $paymentArray = array();
            if(file_exists(DBSHOP_PATH . '/data/moduledata/Payment/' . $paymentCode . '.php')) {
                $paymentArray = include(DBSHOP_PATH . '/data/moduledata/Payment/' . $paymentCode . '.php');
                $postArray['pay_name'] = $paymentArray['payment_name']['content'];
                $postArray['order_state'] = $paymentArray['orders_state'];
                $postArray['payment_code']= $paymentCode;

                //获取支付方式的手续费用，虽然在上一页面有传值过来，但是因为html有可能被恶意更改，因此这里从新获取计算
                $paymentFee = (!empty($paymentArray['payment_fee']['content']) ? ((strpos($paymentArray['payment_fee']['content'], '%') !== false) ? round($cartTotalPrice * str_replace('%', '', $paymentArray['payment_fee']['content']) / 100, 2) : round($this->getServiceLocator()->get('frontHelper')->shopPrice($paymentArray['payment_fee']['content']), 2)) : 0);
            }

            //获取配送方式信息
            $expressArray = array();
            $expressArray = $this->getDbshopTable('ExpressTable')->infoExpress(array('express_id'=>$expressId, 'express_state'=>1));
            $postArray['express_id']   = $expressArray->express_id;
            $postArray['express_name'] = $expressArray->express_name;
            //配送费用获取
            $addressInfo  = $this->getDbshopTable('UserAddressTable')->infoAddress(array('address_id'=>$addressId, 'user_id'=>$userId));//对应下面的收货地址保存
            if(!$addressInfo) return $this->createJson('error', $this->getDbshopLang()->translate('配送地址不匹配！'));

            $regionInfo   = $this->getDbshopTable('RegionTable')->infoRegion(array('dbshop_region.region_id'=>$addressInfo['region_id']));
            $regionIdArray= explode(',', $regionInfo['region_path']);

            $totalWeight = $cart['cart_weight'] * 1000;//将千克换算成克

            $configReader = new \Zend\Config\Reader\Ini();
            $expressConfigFilePath = DBSHOP_PATH . '/data/moduledata/Express/';
            $expressConfig = $configReader->fromFile($expressConfigFilePath . $postArray['express_id'] . '.ini');
            if($expressConfig['express_set'] == 'T') {//当为统一设置时进行的处理
                $expressPrice = $this->getServiceLocator()->get('shop_express')->calculateCost(trim($expressConfig['express_price']), $totalWeight, $cartTotalPrice);
            } else {
                $expressPrice = 0;
                foreach ($expressConfig['express_price'] as $priceValue) {
                    $priceValue['price'] = $this->getServiceLocator()->get('shop_express')->calculateCost(trim($priceValue['price']), $totalWeight, $cartTotalPrice);
                    foreach ($regionIdArray as $regionId) {
                        if(in_array($regionId, $priceValue['area_id'])) {
                            $expressPrice = ($expressPrice > 0 and $expressPrice < $priceValue['price']) ? $expressPrice : $priceValue['price'];
                        }
                    }
                }
            }
            $expressPrice = $this->getServiceLocator()->get('frontHelper')->shopPrice($expressPrice);

            //用户优惠与积分中的计算
            $array['promotionsCost'] = $cart['discount']['discount_cost'];
            //查看是否有优惠券使用
            $userCouponFee = 0;
            $userCouponState = false;
            $userCouponId  = 0;
            if(isset($couponId) and $couponId > 0) {
                $userCoupon = $this->getDbshopTable('UserCouponTable')->infoUserCoupon(array('user_id'=>$userId, 'coupon_use_state'=>1, 'coupon_id'=>$couponId));
                if($userCoupon->user_coupon_id > 0) {
                    $couponFee = CouponRuleService::couponUseRule(array('cartGoods'=>$cart['cart_goods'], 'type'=>'submit_cart', 'coupon_id'=>$userCoupon->coupon_id), '');
                    if($couponFee > 0) {
                        $userCouponFee  = $this->getServiceLocator()->get('frontHelper')->shopPrice($couponFee);
                        $userCouponState= true;
                        $userCouponId   = $userCoupon->user_coupon_id;
                    }
                }
            }
            //订单总金额
            $orderTotalPrice = $expressPrice + $paymentFee + $cartTotalPrice - $array['promotionsCost'] - $userCouponFee;
            //是否使用消费积分购买
            $integralBuyState = false;
            $integralBuyPrice = 0;
            $integralBuyNum   = (isset($integralBuyNum) and $integralBuyNum > 0) ? intval($integralBuyNum) : 0;
            $cartIntegralNum  = $cart['cart_integral_num'];
            $userIntegralInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$userId));
            if($userIntegralInfo->user_integral_num < $integralBuyNum or $integralBuyNum > $cartIntegralNum) $integralBuyNum = 0;//如果会员拥有的积分数小于将要购买使用的积分数或者购买积分数大于购物车中的积分数，则将该购买积分数设置为0，因为无效
            if($integralBuyNum > 0 and $cartIntegralNum > 0) {//只有已经使用的积分数和购物车中的积分数都大于0时，积分购买才开启
                //计算积分被转换为货币后的价值是否超过订单总金额，如果超过，则进行无效处理
                $integralInfo = $this->getDbshopTable('UserIntegralTypeTable')->userIntegarlTypeOneInfo(array('integral_type_id'=>1));
                $integralBuyPrice   = $this->getServiceLocator()->get('frontHelper')->shopPrice($integralInfo->integral_currency_con / 100 * $integralBuyNum);
                if($integralBuyPrice <= 0 or $integralBuyPrice > $orderTotalPrice) {
                    $integralBuyNum     = 0;
                    $integralBuyPrice   = 0;
                } else {
                    $integralBuyState   = true;
                    $orderTotalPrice    = $orderTotalPrice - $integralBuyPrice;
                }
            }
            //判断订单金额
            if($orderTotalPrice < 0) {
                return $this->createJson('error', $this->getDbshopLang()->translate('订单金额不能小于0！'));
            }
            /*----------------------订单相关信息保存----------------------*/
            //开启数据库事务处理
            $this->getDbshopTable('dbshopTransaction')->DbshopTransactionBegin();
            //对post过来的价格信息进行重置，以防止恶意使用者修改html中的数值
            $postArray['goods_total_price'] = $cartTotalPrice;
            $postArray['order_total_price'] = $orderTotalPrice;
            $postArray['pay_price']         = $paymentFee;
            $postArray['express_price']     = $expressPrice;
            $postArray['buy_pre_price']     = $array['promotionsCost'];
            $postArray['user_pre_price']    = 0;//会员优惠暂时没有这个功能
            $postArray['integral_buy_num']  = $integralBuyNum;
            $postArray['integral_buy_price']= $integralBuyPrice;
            $postArray['order_message']     = $orderMessage;
            $postArray['invoice_title']     = $invoiceTitle;
            $postArray['invoice_content']   = $invoiceContent;
            $postArray['integral_num']      = $cart['integral']['integral_num'];
            $postArray['integral_rule_info']= $cart['integral']['integral_info'];
            $postArray['integral_type_2_num']          = $cart['integral_1']['integral_num'];
            $postArray['integral_type_2_num_rule_info']= $cart['integral_1']['integral_info'];

            $orderArray = $this->orderSave($postArray);
            $orderId    = $orderArray['order_id'];

            //消费积分，消费记录保存
            if($integralBuyState) {
                $integralLogArray = array();
                $integralLogArray['user_id']           = $this->userData['user_id'];
                $integralLogArray['user_name']         = $this->userData['user_name'];
                $integralLogArray['integral_log_info'] = $this->getDbshopLang()->translate('商品购物，订单号为：') . $orderArray['order_sn'];
                $integralLogArray['integral_num_log']  = '-'.$integralBuyNum;
                $integralLogArray['integral_log_time'] = time();
                if($this->getDbshopTable('IntegralLogTable')->addIntegralLog($integralLogArray)) {
                    //会员消费积分更新
                    $this->getDbshopTable('UserTable')->updateUserIntegralNum($integralLogArray, array('user_id'=>$integralLogArray['user_id']));
                }
            }
            //保存收货地址
            $this->orderDeliveryAddressSave($addressInfo,
                array(
                    'order_id'=>$orderId,
                    'shipping_time'=>$shippingTime,
                    'express_name'=>$postArray['express_name'],
                    'express_id'=>$postArray['express_id'],
                    'express_fee'=>$postArray['express_price']
                )
            );
            //优惠券使用处理，说明上面已经使用，这里将其状态修改为已经使用
            if($userCouponState and $userCouponId > 0) {
                $this->getDbshopTable('UserCouponTable')->updateUserCoupon(
                    array(
                        'coupon_use_state'  => 2,
                        'used_order_id'     => $orderId,
                        'used_order_sn'     => $orderArray['order_sn'],
                        'used_time'         => time()
                    ),
                    array('user_id'=>$userId, 'user_coupon_id'=>$userCouponId, 'coupon_use_state'=>1));
                //在订单表中加入优惠券优惠金额
                $this->getDbshopTable('OrderTable')->updateOrder(array('coupon_pre_fee'=>$userCouponFee), array('order_id'=>$orderId));
            }
            //保存订单中的商品信息
            $goodsSerialize  = array();
            $goodsStockError = array();
            foreach ($cart['cart_goods'] as $cart_key => $cart_value) {
                //之所以这里再调用一次，是因为添加购物车的时候，对图片进行了处理，当为cdn时，图片也是取的cdn值，所以要在下面转换为本地图片
                $goodsInfo = $this->getDbshopTable('GoodsTable')->infoGoods(array('dbshop_goods.goods_id'=>$cart_value['goods_id']));
                if(!empty($goodsInfo)) $cart_value['goods_image'] = $goodsInfo->goods_thumbnail_image;

                $orderGoodsId = $this->orderGoodsSave($cart_value, array('order_id'=>$orderId));
                if($orderGoodsId != -1) {//库存正确处理
                    $goodsSerialize[$orderGoodsId] = array(
                        'goods_id'          => $cart_value['goods_id'],
                        'class_id'          => $cart_value['class_id'],
                        'goods_name'        => $cart_value['goods_name'],
                        'goods_extend_info' => $cart_value['goods_color_name'] . $cart_value['goods_size_name'] . str_replace('<br>', '  ',$cart_value['goods_adv_tag_name']),
                        'goods_image'       => $cart_value['goods_image'],
                        'goods_type'        => $cart_value['goods_type'],
                        //'goods_shop_price'  => $this->getServiceLocator()->get('frontHelper')->shopPrice($cart_value['goods_shop_price']),
                        'goods_shop_price'  => $cart_value['goods_shop_price'],
                        'buy_num'           => $cart_value['buy_num'],
                        'goods_color'       => isset($cart_value['goods_color']) ? $cart_value['goods_color'] : '',
                        'goods_size'        => isset($cart_value['goods_size']) ? $cart_value['goods_size'] : '',
                        'goods_spec_tag_id' => $cart_value['goods_adv_tag_id']
                    );
                } else {
                    $goodsStockError[] = $cart_value['goods_name'];
                }
            }
            //判断库存是否不足，如果不足，则启用事务回滚功能
            if(!empty($goodsStockError)) {
                $this->getDbshopTable('dbshopTransaction')->DbshopTransactionRollback();//事务回滚
                $errorMessage = implode(',', $goodsStockError) . '&nbsp;&nbsp;' . $this->getDbshopLang()->translate('商品库存不足') . ',' . $this->getDbshopLang()->translate('去购物车中删除库存不足的商品');
                return $this->createJson('error', $errorMessage);
            } else {
                $this->getDbshopTable('dbshopTransaction')->DbshopTransactionCommit();//事务确认
            }

            $this->getDbshopTable('OrderTable')->updateOrder(array('goods_serialize'=>serialize($goodsSerialize)), array('order_id'=>$orderId));
            //事件驱动的数据
            $postArray['order_id']  = $orderId;
            $postArray['other']     =  array(
                'user_id'   => $this->userData['user_id'],
                'user_name' => $this->userData['user_name'],
                'user_group'=> $this->userData['group_id'],
                'cartGoods' => $cart['cart_goods'],
                'order_id'  => $orderId,
                'order_sn'  => $orderArray['order_sn']
            );
            //清空购物车操作
            $this->getDbshopTable('ApiCartTable')->delCart(array('user_unionid'=>$userUnionid));
            /*----------------------订单相关信息保存----------------------*/

            $orderJsonArray['order_sn']    = $orderArray['order_sn'];
            $orderJsonArray['order_id']    = $orderId;
            $orderJsonArray['order_state'] = $postArray['order_state'];
            $orderJsonArray['order_total'] = $this->getServiceLocator()->get('frontHelper')->shopPriceSymbol() . $postArray['order_total_price'] . $this->getServiceLocator()->get('frontHelper')->shopPriceUnit();

            //事件驱动
            $this->getEventManager()->trigger('cart.submit.front.post', $this, $postArray);

            //下面内容为email和手机提醒信息的公共使用内容
            $sendArray = array();
            $sendArray['shopname']      = $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name');
            $sendArray['buyname']       = $this->userData['user_name'];
            $sendArray['ordersn']       = $array['order_sn'];
            $sendArray['ordertotal']    = $array['order_total'];
            $sendArray['submittime']    = $orderArray['order_time'];
            $sendArray['shopurl']       = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost() . $this->url()->fromRoute('shopfront/default');

            /*----------------------提醒信息发送----------------------*/
            $sendMessageBody = $this->getServiceLocator()->get('frontHelper')->getSendMessageBody('submit_order');
            if($sendMessageBody != '') {
                $sendArray['subject']       = $sendArray['shopname'] . $this->getDbshopLang()->translate('提交订单提醒');
                $sendArray['send_mail'][]   = $this->getServiceLocator()->get('frontHelper')->getSendMessageBuyerEmail('submit_order_state', $this->userData['user_email']);
                $sendArray['send_mail'][]   = $this->getServiceLocator()->get('frontHelper')->getSendMessageAdminEmail('submit_order_state');

                $sendMessageBody            = $this->getServiceLocator()->get('frontHelper')->createSendMessageContent($sendArray, $sendMessageBody);
                try {
                    $sendState = $this->getServiceLocator()->get('shop_send_mail')->SendMesssageMail($sendArray, $sendMessageBody);
                    $sendState = ($sendState ? 1 : 2);
                } catch (\Exception $e) {
                    $sendState = 2;
                }
                //记录给用户发的电邮
                if($sendArray['send_mail'][0] != '') {
                    $sendLog = array(
                        'mail_subject' => $sendArray['subject'],
                        'mail_body'    => $sendMessageBody,
                        'send_time'    => time(),
                        'user_id'      => $this->userData['user_id'],
                        'send_state'   => $sendState
                    );
                    $this->getDbshopTable('UserMailLogTable')->addUserMailLog($sendLog);
                }
            }
            /*----------------------提醒信息发送----------------------*/

            /*----------------------手机短信信息发送----------------------*/
            $smsData = array(
                'shopname'   => $sendArray['shopname'],
                'buyname'    => $sendArray['buyname'],
                'ordersn'    => $sendArray['ordersn'],
                'submittime' => $sendArray['submittime'],
                'ordertotal' => $sendArray['ordertotal']
            );
            try {
                $this->getServiceLocator()->get('shop_send_sms')->toSendSms(
                    $smsData,
                    $this->userData['user_phone'],
                    'alidayu_submit_order_template_id',
                    $this->userData['user_id']
                );
            } catch(\Exception $e) {

            }
            /*----------------------手机短信信息发送----------------------*/

        }

        if(!empty($orderJsonArray)) return $this->createJsonData($orderJsonArray);
        else return $this->createJson('error', $this->getDbshopLang()->translate('订单添加失败！'));
    }
    /*============================================订单提交相关============================================*/

    /*============================================用户中心相关============================================*/
    /**
     * 获取用户信息
     * post
     * user_token   必填，用户登录唯一标识
     * @return JsonModel
     */
    public function userInfoAction()
    {
        $status     = 'error';
        $userInfo   = array();
        if(is_array($this->userData) and !empty($this->userData)) {
            $info = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$this->userData['user_id']));
            if(!empty($info)) {
                $status = 'success';
                $userInfo                           = $this->userData;
                $userInfo['user_sex']               = $info->user_sex;              //性别，1 男，2 女，3 保密
                $userInfo['user_birthday']          = $info->user_birthday;         //生日
                $userInfo['user_integral_num']      = $info->user_integral_num;     //消费积分数
                $userInfo['integral_type_2_num']    = $info->integral_type_2_num;   //等级积分数
                $userInfo['user_money']             = $info->user_money;            //账户余额
                $userInfo['user_phone']             = $info->user_phone;            //手机号码

                //事件驱动，显示客户信息时的处理
                $response = $this->getEventManager()->trigger('user.info.front.post', $this, array('values'=>$userInfo));
                if(!$response->isEmpty()) {
                    $num = $response->count();
                    for($i = 0; $i < $num; $i++) {
                        $preArray = $response->offsetGet($i);
                        if(!empty($preArray)) {
                            //$array[key($preArray)] = current($preArray);
                            $userInfo[key($preArray)] = current($preArray);
                        }
                        unset($preArray);
                    }
                }
            }
        }

        return $this->createJsonData($userInfo, $status);
    }
    /**
     * 保存用户信息
     * post
     * user_token       必填，用户登录唯一标识
     * user_email       必填，用户电子邮箱
     * user_sex         必填，用户性别
     * user_phone       非必填，用户电话号码
     * user_birthday    非必填，用户生日
     * user_avatar      非必填，用户头像
     *
     * @return JsonModel
     */
    public function saveUserAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('信息更新失败！');

        $userId = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id
        if($userId > 0 and !empty($this->postData)) {
            $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$this->userData['user_id']));
            $saveArray = array();
            $saveArray['user_sex']      = intval($this->postData['user_sex']);
            $saveArray['user_birthday'] = isset($this->postData['user_birthday']) ? trim($this->postData['user_birthday']) : '';

            //判断注册项中是否开启了邮箱注册
            $userEmailRegisterState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('register_email_state');
            if($userEmailRegisterState == 'true' and empty($this->postData['user_email'])) return $this->createJson($status, $this->getDbshopLang()->translate('Email不能为空！'));
            if(!empty($this->postData['user_email'])) {
                $emailValid = new EmailAddress();
                if(!$emailValid->isValid($this->postData['user_email'])) {
                    return $this->createJson($status, $this->getDbshopLang()->translate('Email格式不正确！'));
                }
                $checkUserEmail = $this->checkUserEmail($this->postData['user_email'], $userId);
                if(!$checkUserEmail['status']) {
                    return $this->createJson($status, $checkUserEmail['message']);
                }
                $saveArray['user_email']    = trim($this->postData['user_email']);
            }

            //判断注册项中是否开启手机号码
            $userPhoneRegisterState = $this->getServiceLocator()->get('frontHelper')->getRegOrLoginIni('register_phone_state');
            if($userPhoneRegisterState == 'true' and empty($this->postData['user_phone'])) return $this->createJson($status, $this->getDbshopLang()->translate('电话号码不能为空！'));
            if(!empty($this->postData['user_phone'])) {
                $checkUserPhone = $this->checkUserPhone($this->postData['user_phone'], $userId);
                if(!$checkUserPhone['status']) {
                    return $this->createJson($status, $checkUserPhone['message']);
                }
                $saveArray['user_phone']    = trim($this->postData['user_phone']);
            }

            $saveArray['old_user_avatar'] = (isset($userInfo->user_avatar) and !empty($userInfo->user_avatar)) ? $userInfo->user_avatar : '';
            //会员头像上传
            $userAvatar = $this->getServiceLocator()->get('shop_other_upload')->userAvatarUpload($userId, 'user_avatar', (isset($saveArray['old_user_avatar']) ? $saveArray['old_user_avatar'] : ''), $this->getServiceLocator()->get('adminHelper')->defaultShopSet('shop_user_avatar_width'), $this->getServiceLocator()->get('adminHelper')->defaultShopSet('shop_user_avatar_height'));
            $saveArray['user_avatar'] = $userAvatar['image'];

            $this->getDbshopTable('UserTable')->updateUser($saveArray, array('user_id'=>$userId));

            $userGroup = $this->getDbshopTable('UserGroupExtendTable')->infoUserGroupExtend(array('group_id'=>$userInfo->group_id,'language'=>$this->getDbshopLang()->getLocale()));
            //这里再进行一次会员获取，更新后的获取，为了下面的更新信息
            $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$userId));
            $user_serialize = array(
                'user_name'      => $userInfo->user_name,
                'user_id'        => $userInfo->user_id,
                'user_email'     => $userInfo->user_email,
                'user_phone'     => $userInfo->user_phone,
                'group_id'       => $userInfo->group_id,
                'user_group_name'=> $userGroup->group_name,
                'user_avatar'    => (!empty($userInfo->user_avatar) ? $userInfo->user_avatar : $this->getServiceLocator()->get('frontHelper')->getUserIni('default_avatar'))
            );
            $userLoginInfo = array(
                'user_serialize'=> serialize($user_serialize)
            );
            //更新登录信息存储
            $this->getDbshopTable('ApiUserLoginTable')->updateUserLogin($userLoginInfo, array('user_id'=>$userInfo->user_id));

            $status = 'success';
            $msg    = $this->getDbshopLang()->translate('信息更新成功！');
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 用户密码修改
     * post
     * user_token           必填，用户登录唯一标识
     * old_user_password    必填，原密码
     * user_password        必填，新密码
     * user_com_passwd      必填，确认密码（新密码）
     *
     * @return JsonModel
     */
    public function saveUserPasswdAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('密码修改失败！');

        $userId = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id
        if($userId > 0 and !empty($this->postData['old_user_password']) and !empty($this->postData['user_password']) and !empty($this->postData['user_com_passwd'])) {
            //判断密码与确认密码是否一致
            if($this->postData['user_password'] != $this->postData['user_com_passwd']) return $this->createJson($status, $this->getDbshopLang()->translate('两次输入的密码不同，请重新输入！'));
            //旧密码判断
            $where = array(
                'user_password' => $this->getServiceLocator()->get('frontHelper')->getPasswordStr($this->postData['old_user_password']),
                'user_id'       => $userId
            );
            $userInfo = $this->getDbshopTable('UserTable')->infoUser($where);
            if(empty($userInfo)) return $this->createJson($status, $this->getDbshopLang()->translate('原始密码输入错误，请重新输入！'));
            //密码修改处理
            $passwdArray['user_password'] = $this->getServiceLocator()->get('frontHelper')->getPasswordStr(trim($this->postData['user_password']));
            $this->getDbshopTable('UserTable')->updateUser($passwdArray, array('user_id'=>$userId));

            $status = 'success';
            $msg    = $this->getDbshopLang()->translate('密码修改成功！');
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 我的收藏（商品收藏）
     * get
     * user_token   必填，用户登录唯一标识
     * page         必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty          必填，每页显示的商品数量，如果不填写默认是 10
     * @return JsonModel
     */
    public function favoritesGoodsAction()
    {
        $userId     = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id
        $goodsList  = array();

        if($userId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'] = array('user_id'=>$userId);

            $goodsList = $this->getDbshopTable('ApiFavoritesTable')->favoritesGoodsListPage($array);

            if(is_array($goodsList) and !empty($goodsList)) {//进行图片地址转换，转换为公网可访问地址
                foreach($goodsList as $key => $value) {
                    $goodsList[$key]['goods_thumbnail_image'] = $this->createDbshopImageUrl($value['goods_thumbnail_image']);
                    $goodsList[$key]['goods_title_image']     = $this->createDbshopImageUrl($value['goods_title_image']);
                }
            }
        }

        return $this->createJsonData($goodsList);
    }
    /**
     * 收藏商品删除
     * post
     * user_token   必填，用户登录唯一标识
     * favorites_id 必填，收藏商品id
     * @return JsonModel
     */
    public function delFavoritesGoodsAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('收藏商品删除失败！');

        $userId     = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id
        $favoritesId= isset($this->postData['favorites_id']) ? intval($this->postData['favorites_id']) : 0;//收藏商品id
        if($userId > 0 and $favoritesId > 0) {
            $this->getDbshopTable('UserFavoritesTable')->delFavorites(array('favorites_id'=>$favoritesId, 'user_id'=>$userId));

            $status = 'success';
            $msg    = $this->getDbshopLang()->translate('收藏商品删除成功！');
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 会员中心我的咨询
     * get
     * user_token   必填，用户登录唯一标识
     * page         必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty          必填，每页显示的商品数量，如果不填写默认是 10
     * @return JsonModel
     */
    public function homeGoodsAskAction()
    {
        $userId     = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id
        $goodsAsk    = array();
        if($userId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'] = array('dbshop_goods_ask.ask_writer'=>$this->userData['user_name'], 'e.language'=>$this->getDbshopLang()->getLocale());

            $goodsAsk = $this->getDbshopTable('ApiGoodsAskTable')->listGoodsAsk($array);
        }
        return $this->createJsonData($goodsAsk);
    }
    /**
     * 会员中心我的咨询删除
     * post
     * user_token   必填，用户登录唯一标识
     * ask_id       必填，咨询id
     * @return JsonModel
     */
    public function homeGoodsAskDelAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('商品咨询删除失败！');

        $userId = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id
        $askId  = isset($this->postData['ask_id']) ? intval($this->postData['ask_id']) : 0;//咨询id
        if($userId > 0 and $askId > 0) {
            $this->getDbshopTable('ApiGoodsAskTable')->delGoodsAsk(array('ask_id'=>$askId, 'ask_writer'=>$this->userData['user_name']));

            $status = 'success';
            $msg    = $this->getDbshopLang()->translate('商品咨询删除成功！');
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 获取最新订单列表（这里获取的订单不包括 被取消的订单 和 已经完成的订单）
     * post
     * user_token   必填，用户登录唯一标识
     * order_num    非必填，获取订单数量，如果不填写，默认是5
     * @return JsonModel
     */
    public function newOrderAction()
    {
        $userId     = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id
        $orderNum   = isset($this->postData['order_num']) ? intval($this->postData['order_num']) : 6;//订单数量
        $orderList = array();
        if($userId > 0) {
            $orderList = $this->getDbshopTable('ApiOrderTable')->allOrder(array('buyer_id'=>$userId, 'order_state NOT IN (0,60)'), $orderNum);
            //将订单里的商品信息反序列化
            if(is_array($orderList) and !empty($orderList)) {
                foreach($orderList as $oKey => $oValue) {
                    $oValue['goods'] = unserialize($oValue['goods_serialize']);
                    unset($oValue['goods_serialize']);
                    $orderList[$oKey] = $oValue;
                }
            }
        }

        return $this->createJsonData($orderList);
    }
    /**
     * 获取订单列表
     * get
     * user_token   必填，用户登录唯一标识
     * order_state  非必填，默认是全部订单（0 已取消，10 待付款[有效订单]，15 付款中，20 已付款， 30 待发货，40 已发货，60 已完成）
     * order_sn     非必填，订单编号，用户订单检索
     * page         必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty          必填，每页显示的商品数量，如果不填写默认是 10
     * @return JsonModel
     */
    public function orderListAction()
    {
        $userId     = isset($this->userData['user_id'])     ? intval($this->userData['user_id'])    : 0;//用户id
        $orderState = isset($this->getData['order_state'])  ? intval($this->getData['order_state']) : '';//订单状态
        $orderSn    = isset($this->getData['order_sn'])     ? intval($this->getData['order_sn'])    : '';//订单编号
        $orderList  = array();
        if($userId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'] = array('dbshop_order.buyer_id'=>$userId);
            if($orderState != '') {
                $orderState = in_array($orderState, array(-40, 5, 12, 30, 10, 15, 20, 30, 40, 60)) ? $orderState : 10;
                if($orderState == -40) $array['where']['dbshop_order.refund_state'] = 1;
                else {
                    if(!in_array($orderState, array(5, 12, 30))) $array['where']['dbshop_order.order_state'] = $orderState;
                    if($orderState == 12) $array['where'][] = "dbshop_order.order_state >= 10 and dbshop_order.order_state < 20";
                    if($orderState == 30) $array['where'][] = "dbshop_order.order_state >= 20 and dbshop_order.order_state < 40";
                    $array['where']['dbshop_order.refund_state'] = '0';
                }
            }

            if(!empty($orderSn)) $array['where']['search_order_sn'] = $orderSn;
            $orderList = $this->getDbshopTable('ApiOrderTable')->orderPageList($array);
            //将订单里的商品信息反序列化
            if(is_array($orderList) and !empty($orderList)) {
                foreach($orderList as $oKey => $oValue) {
                    $oValue['order_state_name'] = $this->getServiceLocator()->get('frontHelper')->getOneOrderStateInfo($oValue['order_state']);
                    $oValue['order_time_text']  = date("Y-m-d H:i:s", $oValue['order_time']);
                    $oValue['goods'] = array();
                    foreach (unserialize($oValue['goods_serialize']) as $goodsKey => $goodsValue) {
                        $goodsValue['goods_image']      = $this->createDbshopImageUrl($goodsValue['goods_image']);
                        $goodsValue['order_goods_id']   = $goodsKey;
                        $oValue['goods'][]              = $goodsValue;
                    }
                    unset($oValue['goods_serialize']);

                    $orderList[$oKey] = $oValue;
                }
            }
        }

        return $this->createJsonData($orderList);
    }
    /**
     * 获取订单详情
     * post
     * user_token   必填，用户登录唯一标识
     * order_id     必填，订单id
     * @return JsonModel
     */
    public function showOrderAction()
    {
        $userId  = isset($this->userData['user_id'])    ? intval($this->userData['user_id'])    : 0;//用户id
        $orderId = isset($this->postData['order_id'])   ? intval($this->postData['order_id'])   : 0;//订单id

        $array   = array();
        if($userId > 0 and $orderId > 0) {
            //订单内容
            $array['order_info'] = $this->getDbshopTable('OrderTable')->infoOrder(array('order_id'=>$orderId, 'buyer_id'=>$userId));
            if(!$array['order_info']) return $this->createJson('error', $this->getDbshopLang()->translate('该订单不存在！'));
            unset($array['order_info']['goods_serialize']);
            //订单配送信息
            $array['delivery_address'] = $this->getDbshopTable('OrderDeliveryAddressTable')->infoDeliveryAddress(array('order_id'=>$orderId));

            //订单商品
            $array['order_goods'] = $this->getDbshopTable('OrderGoodsTable')->listOrderGoods(array('order_id'=>$orderId));
            foreach ($array['order_goods'] as $key => $value) {
                $array['order_goods'][$key]['goods_extend_info'] = strip_tags($value['goods_extend_info']);
                $array['order_goods'][$key]['goods_image'] = $this->createDbshopImageUrl($value['goods_image']);
            }

            //订单总价修改历史
            $array['order_amount_log'] = $this->getDbshopTable('OrderAmountLogTable')->listOrderAmountLog(array('order_id'=>$orderId));

            //退货信息
            if($array['order_info']->refund_state == 1) {
                $array['refund_order'] = $this->getDbshopTable('OrderRefundTable')->infoOrderRefund(array('order_sn'=>$array['order_info']->order_sn));
                $array['refund_order'] = (array) $array['refund_order'];
            }

            $array['order_info'] = (array) $array['order_info'];
            $array['order_info']['order_state_name'] = $this->getServiceLocator()->get('frontHelper')->getOneOrderStateInfo($array['order_info']['order_state']);
            $array['order_info']['order_time_text']  = date("Y-m-d H:i:s", $array['order_info']['order_time']);
            $array['order_info']['pay_time_text']    = !empty($array['order_info']['pay_time']) ? date("Y-m-d H:i:s", $array['order_info']['pay_time']) : '';
            $array['order_info']['express_time_text']= !empty($array['order_info']['express_time']) ? date("Y-m-d H:i:s", $array['order_info']['express_time']) : '';
            $array['order_info']['finish_time_text'] = !empty($array['order_info']['finish_time']) ? date("Y-m-d H:i:s", $array['order_info']['finish_time']) : '';

            //物流状态信息
            if($array['order_info']['order_state'] >= 40 and $array['delivery_address']['express_number'] != '') {
                $iniReader   = new \Zend\Config\Reader\Ini();
                $expressPath = DBSHOP_PATH . '/data/moduledata/Express/';
                if(file_exists($expressPath . $array['order_info']['express_id'] . '.ini')) {
                    $expressIni = $iniReader->fromFile($expressPath . $array['order_info']['express_id'] . '.ini');
                    $array['express_url'] = $expressIni['express_url'];
                    if(is_array($expressIni) and $expressIni['express_name_code'] != '' and file_exists($expressPath . 'express.php')) {
                        $expressArray = include($expressPath . 'express.php');
                        if(!empty($expressArray)) {
                            $expressStateArray = $this->getServiceLocator()->get('shop_express_state')->getExpressStateContent($expressArray, $expressIni['express_name_code'], $array['delivery_address']['express_number']);
                            if($expressStateArray['api_type'] == 'kuaidi100') $array['express_content'] = $expressStateArray['content'];
                        }
                    }
                }
            }
        }

        return $this->createJsonData($array);
    }
    /**
     * 取消订单
     * post
     * user_token   必填，用户登录唯一标识
     * order_id     必填，订单id
     * @return JsonModel
     */
    public function cancelOrderAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('该订单取消失败！');

        $userId  = isset($this->userData['user_id'])    ? intval($this->userData['user_id'])    : 0;//用户id
        $orderId = isset($this->postData['order_id'])   ? intval($this->postData['order_id'])   : 0;//订单id
        if($userId > 0 and $orderId > 0) {
            $orderInfo    = $this->getDbshopTable('OrderTable')->infoOrder(array('order_id'=>$orderId, 'buyer_id'=>$userId));
            if(($orderInfo->order_state == 10 or ($orderInfo->order_state == 30 and $orderInfo->pay_code == 'hdfk')) and !empty($orderInfo)) {//取消订单处理
                $this->getDbshopTable('OrderTable')->updateOrder(array('order_state'=>0), array('order_id'=>$orderId));
                $this->returnGoodsStock($orderId);//取消订单时的库存处理

                //加入状态记录
                $this->getDbshopTable('OrderLogTable')->addOrderLog(array('order_id'=>$orderId, 'order_state'=>'0', 'state_info'=>$this->getDbshopLang()->translate('买家自行取消'), 'log_time'=>time(), 'log_user'=>$this->userData['user_name']));

                //检查是否有消费积分付款
                if($orderInfo->integral_buy_num > 0) {
                    $integralLogArray = array();
                    $integralLogArray['user_id']           = $userId;
                    $integralLogArray['user_name']         = $this->userData['user_name'];
                    $integralLogArray['integral_log_info'] = $this->getDbshopLang()->translate('取消订单，订单号为：') . $orderInfo->order_sn;
                    $integralLogArray['integral_num_log']  = $orderInfo->integral_buy_num;
                    $integralLogArray['integral_log_time'] = time();
                    if($this->getDbshopTable('IntegralLogTable')->addIntegralLog($integralLogArray)) {
                        //会员消费积分更新
                        $this->getDbshopTable('UserTable')->updateUserIntegralNum($integralLogArray, array('user_id'=>$integralLogArray['user_id']));
                    }
                }
                /*----------------------提醒信息发送----------------------*/
                $sendArray['buyer_name']  = $orderInfo->buyer_name;
                $sendArray['order_sn']    = $orderInfo->order_sn;
                $sendArray['order_total'] = $orderInfo->order_amount;
                $sendArray['time']        = time();
                $sendArray['buyer_email'] = $orderInfo->buyer_email;
                $sendArray['order_state'] = 'cancel_order';
                $sendArray['time_type']   = 'canceltime';
                $sendArray['subject']     = $this->getDbshopLang()->translate('订单取消');
                $this->changeStateSendMail($sendArray);
                /*----------------------提醒信息发送----------------------*/

                /*----------------------手机提醒信息发送----------------------*/
                $smsData = array(
                    'buyname'   => $sendArray['buyer_name'],
                    'ordersn'    => $sendArray['order_sn'],
                    'ordertotal'=> $sendArray['order_total'],
                    'time'    => $sendArray['time'],
                );
                try {
                    $this->getServiceLocator()->get('shop_send_sms')->toSendSms(
                        $smsData,
                        $this->userData['user_phone'],
                        'alidayu_cancel_order_template_id',
                        $userId
                    );
                } catch(\Exception $e) {

                }
                /*----------------------手机提醒信息发送----------------------*/

                $this->getEventManager()->trigger('order.cancel.front.post', $this, array('values'=>$orderId));

                $status = 'success';
                $msg    = $this->getDbshopLang()->translate('该订单取消成功！');
            }
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 删除订单（必须是已经取消的订单才可以被删除）
     * post
     * user_token   必填，用户登录唯一标识
     * order_id     必填，订单id
     * @return JsonModel
     */
    public function delOrderAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('该订单删除失败！');

        $userId  = isset($this->userData['user_id'])    ? intval($this->userData['user_id'])    : 0;//用户id
        $orderId = isset($this->postData['order_id'])   ? intval($this->postData['order_id'])   : 0;//订单id
        if($userId > 0 and $orderId > 0) {
            $orderInfo    = $this->getDbshopTable('OrderTable')->infoOrder(array('order_id'=>$orderId, 'buyer_id'=>$userId));
            if($orderInfo && $orderInfo->order_state == 0) {
                $this->getDbshopTable('OrderTable')->delOrder(array('order_id'=>$orderId));
                //事件驱动
                $this->getEventManager()->trigger('order.del.front.post', $this, array('values'=>$orderInfo));

                $status = 'success';
                $msg    = $this->getDbshopLang()->translate('该订单删除成功！');
            }
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 订单商品退货申请
     * post
     * user_token       必填，用户登录唯一标识
     * order_goods_id   必填，订单商品id（注意订单商品id与商品id是两个不同的值，不要混淆）
     * order_id         必填，订单id
     * refund_type      必填，退款方式（1 退款到账户余额、2 退款到银行卡、3、退款到第三方支付）
     * refund_info      必填，退货原因
     * bank_name        选填，（开户行或支付名称）退款方式为 2或者3时，此值必填
     * bank_account     选填，（姓名）退款方式为 2或者3时，此值必填
     * bank_card_number 选填，（收款卡号或者收款账号）退款方式为 2或者3时，此值必填
     * @return JsonModel
     */
    public function submitRefundOrderGoodsAction()
    {
        $userId         = isset($this->userData['user_id'])             ? intval($this->userData['user_id']) : 0;  //用户id
        $orderId        = isset($this->postData['order_id'])            ? intval($this->postData['order_id']) : 0;
        $orderGoodsId   = isset($this->postData['order_goods_id'])      ? intval($this->postData['order_goods_id']) : 0;
        $refundType     = isset($this->postData['refund_type'])         ? intval($this->postData['refund_type']) : 0;
        $refundInfo     = isset($this->postData['refund_info'])         ? trim($this->postData['refund_info']) : '';
        $bankName       = isset($this->postData['bank_name'])           ? trim($this->postData['bank_name']) : '';
        $bankAccount    = isset($this->postData['bank_account'])        ? trim($this->postData['bank_account']) : '';
        $cardNumber     = isset($this->postData['bank_card_number'])    ? trim($this->postData['bank_card_number']) : '';

        if($orderId > 0 and $userId > 0 and $orderGoodsId > 0 and in_array($refundType, array(1, 2, 3)) and !empty($refundInfo)) {
            $orderInfo = $this->getDbshopTable('OrderTable')->infoOrder(array('order_id'=>$orderId, 'buyer_id'=>$userId, 'order_state>=40'));
            if(!$orderInfo) return $this->createJson('error', $this->getDbshopLang()->translate('该订单不具备退货条件！'));

            $goodsRefund = $this->getDbshopTable('OrderRefundTable')->listOrderRefundGoods(array('order_id'=>$orderId, 'user_id'=>$userId));
            if(is_array($goodsRefund) and !empty($goodsRefund)) {
                foreach($goodsRefund as $reValue) {
                    $orderGoodsIdArray = explode(',', $reValue['goods_id_str']);
                    if(in_array($orderGoodsId, $orderGoodsIdArray)) {
                        return $this->createJson('error', $this->getDbshopLang()->translate('该商品已经申请过退货，不能重复申请！'));
                    }
                }
            }

            $refundState = $this->getServiceLocator()->get('frontHelper')->getOrderConfig('user_order_refund');
            if((isset($refundState) and $refundState != 'true') or !isset($refundState)) {
                return $this->createJson('error', $this->getDbshopLang()->translate('退货功能没有开启'));
            } else {
                $timeLimit = (int) $this->getServiceLocator()->get('frontHelper')->getOrderConfig('refund_time_limit');
                if($timeLimit > 0 && !empty($orderInfo['finish_time'])) {
                    $oneDayTime = 60 * 60 * 24;
                    $limitTime  = $oneDayTime * $timeLimit;
                    if(time() - $orderInfo['finish_time'] > $limitTime) {
                        return $this->createJson('error', $this->getDbshopLang()->translate('已过退货期限'));
                    }
                }
            }

            $orderRefund = array();
            if($refundType == 2 or $refundType == 3) {
                if(empty($bankName) or empty($bankAccount) or empty($cardNumber)) return $this->createJson('error', $this->getDbshopLang()->translate('信息提交不完整，无法申请退货！'));

                $orderRefund['bank_name']        = $bankName;;
                $orderRefund['bank_account']     = $bankAccount;
                $orderRefund['bank_card_number'] = $cardNumber;
            }
            $orderRefund['order_sn']     = $orderInfo->order_sn;
            $orderRefund['order_id']     = $orderId;
            $orderRefund['goods_id_str'] = $orderGoodsId;
            $orderRefund['refund_type']  = $refundType;
            $orderRefund['refund_info']  = $refundInfo;
            $orderRefund['user_id']      = $userId;
            $orderRefund['user_name']    = $this->userData['user_name'];
            $state = $this->getDbshopTable('OrderRefundTable')->addOrderRefund($orderRefund);
            if($state) return $this->createJson('success', $this->getDbshopLang()->translate('退货申请提交成功！'));
        }

        return $this->createJson('error', $this->getDbshopLang()->translate('提交退货商品失败，提交的信息不完整！'));
    }
    /**
     * 订单退货商品列表
     * get
     * user_token   必填，用户登录唯一标识
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * @return JsonModel
     */
    public function listRefundOrderGoodsAction()
    {
        $userId = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;  //用户id

        if($userId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'][] = 'order_goods.buyer_id='.$userId;
            $array['where'][] = 'order_goods.order_goods_id IN (SELECT re.goods_id_str FROM dbshop_order_refund as re WHERE re.user_id='.$userId.')';

            $goodsList = $this->getDbshopTable('ApiOrderGoodsTable')->listRefundOrderGoodsPage($array);
            if(is_array($goodsList) and !empty($goodsList)) {
                foreach($goodsList as $key => $value) {
                    $value['goods_image'] = $this->createDbshopImageUrl($value['goods_image']);
                    $goodsList[$key] = $value;
                }
            }
            return $this->createJsonData($goodsList);
        }
        return $this->createJsonData(array(), 'error');
    }
    /**
     * 订单商品列表
     * get
     * user_token   必填，用户登录唯一标识
     * state    选填，默认显示全部，0为未评价，1为已评价（只有订单完成（60）内的商品才能进行评价）
     * order_state 选填，默认为订单完成状态
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * @return JsonModel
     */
    public function listOrderGoodsAction()
    {
        $userId         = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;  //用户id
        $commentState   = isset($this->getData['state'])    ? intval($this->getData['state'])    : -1; //评价状态
        $orderState     = isset($this->getData['order_state']) ? intval($this->getData['order_state'])    : 60; //订单状态
        $listOrderGoods = array();

        if($userId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'][] = 'o.buyer_id='.$userId;
            $array['where'][] = 'o.order_state='.$orderState;
            $array['where'][] = 'order_goods.order_goods_id NOT IN (SELECT rf.goods_id_str FROM dbshop_order_refund AS rf WHERE rf.order_id=order_goods.order_id)';

            if($commentState >= 0) $array['where'][] = 'order_goods.comment_state='.$commentState;

            $goodsList = $this->getDbshopTable('ApiOrderGoodsTable')->listOrderGoodsPage($array);
            if(is_array($goodsList) and !empty($goodsList)) {
                foreach($goodsList as $key => $value) {
                    if(!isset($listOrderGoods[$value['order_sn']])) {
                        $listOrderGoods[$value['order_sn']] = array(
                            'order_sn'    => $value['order_sn'],
                            'order_state' => $value['order_state'],
                            'order_time'  => $value['order_time'],
                            'pay_time'    => $value['pay_time'],
                            'express_time'=> $value['express_time'],
                            'finish_time' => $value['finish_time'],
                        );
                    }
                    $value['goods_image'] = $this->createDbshopImageUrl($value['goods_image']);
                    unset(
                        $value['order_state'],
                        $value['order_time'],
                        $value['express_time'],
                        $value['finish_time']
                    );
                    $listOrderGoods[$value['order_sn']]['goods_list'][] = $value;
                }
            }
            return $this->createJsonData($listOrderGoods);
        }

        return $this->createJsonData($listOrderGoods, 'error');
    }
    /**
     * 获取该订单商品的评论信息（如果已经评论，返回评论信息）
     * get
     * user_token   必填，用户登录唯一标识
     * order_id     必填，订单id
     * order_goods_id   必填，订单商品id
     */
    public function orderGoodsCommentAction()
    {
        $userId         = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;  //用户id
        $orderGoodsId   = isset($this->getData['order_goods_id']) ? intval($this->getData['order_goods_id']) : 0; //订单商品id
        $orderId        = isset($this->getData['order_id'])   ? intval($this->getData['order_id'])   : 0;//订单id
        $orderGoodsCommnet = array();
        if($userId > 0 and $orderGoodsId > 0) {
            $orderInfo = $this->getDbshopTable('OrderTable')->infoOrder(array('order_state>=60', 'order_id'=>$orderId, 'buyer_id'=>$userId));
            if(empty($orderInfo)) return $this->createJson('error', $this->getDbshopLang()->translate('该订单不存在！'));
            $orderGoodsCommnet['order_id'] = $orderId;
            $orderGoodsCommnet['order_sn'] = $orderInfo->order_sn;

            $orderGoodsInfo = $this->getDbshopTable('ApiOrderGoodsTable')->infoOrderGoods(array('order_id'=>$orderId, 'order_goods_id'=>$orderGoodsId));
            if(empty($orderGoodsInfo)) return $this->createJson('error', $this->getDbshopLang()->translate('该商品不存在！'));
            $orderGoodsInfo->goods_image = $this->createDbshopImageUrl($orderGoodsInfo->goods_image);
            $orderGoodsCommnet = array_merge($orderGoodsCommnet, (array)$orderGoodsInfo);

            if($orderGoodsCommnet['comment_state'] == 1) {
                $commentInfo = $this->getDbshopTable('ApiGoodsCommentTable')->infoGoodsComment(array('order_goods_id'=>$orderGoodsId));
                if(!empty($commentInfo)) {
                    $orderGoodsCommnet = array_merge($orderGoodsCommnet, (array)$commentInfo);
                }
            }
            return $this->createJsonData($orderGoodsCommnet);
        }
        return $this->createJsonData($orderGoodsCommnet, 'error', $this->getDbshopLang()->translate('获取评论失败！'));
    }
    /**
     * 提交商品评价信息
     * post
     * user_token   必填，用户登录唯一标识
     * order_goods_id   必填，订单商品id
     * comment_body 必填 评价内容
     * goods_evaluation 必填，商品评分，1~5，如果不填写默认是5
     */
    public function submitOrderGoodsCommentAction()
    {
        $userId         = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;  //用户id
        $orderGoodsId   = isset($this->postData['order_goods_id']) ? intval($this->postData['order_goods_id']) : 0; //订单商品id
        $commentBody    = isset($this->postData['comment_body']) ? trim($this->postData['comment_body']) : '';      //评价内容
        $goodsEvaluation= isset($this->postData['goods_evaluation']) ? intval($this->postData['goods_evaluation']) : 5;

        if($goodsEvaluation < 0 or $goodsEvaluation > 5) $goodsEvaluation = 5;

        if($userId > 0 and $orderGoodsId > 0) {
            $orderGoodsInfo = $this->getDbshopTable('ApiOrderGoodsTable')->infoOrderGoods(array('buyer_id'=>$userId, 'order_goods_id'=>$orderGoodsId));
            if(!$orderGoodsInfo) return $this->createJson('error', $this->getDbshopLang()->translate('该订单商品不存在！'));
            if($orderGoodsInfo->comment_state == 1) return $this->createJson('error', $this->getDbshopLang()->translate('该订单商品已经评价，不能重复评价！'));

            $orderInfo = $this->getDbshopTable('OrderTable')->infoOrder(array('order_state>=60', 'order_id'=>$orderGoodsInfo->order_id, 'buyer_id'=>$userId));
            if(!$orderInfo) return $this->createJson('error', $this->getDbshopLang()->translate('订单只有在完成状态时，才能进行评价！'));

            $commentArray = array(
                'comment_writer'  => $this->userData['user_name'],
                'comment_time'    => time(),
                'goods_id'        => $orderGoodsInfo->goods_id,
                'order_goods_id'  => $orderGoodsInfo->order_goods_id,
                'goods_evaluation'=> $goodsEvaluation,
                'comment_body'    => $this->filterEmoji($commentBody)
            );

            if($this->getDbshopTable('GoodsCommentTable')->addGoodsComment($commentArray)) {
                $listCommentArray = $this->getDbshopTable('GoodsCommentTable')->allGoodsComment(array('goods_id'=>$orderGoodsInfo->goods_id));
                if(is_array($listCommentArray) and !empty($listCommentArray)) $commentCount = count($listCommentArray); else $commentCount = 1;

                //添加订单商品基础评价
                $baseCommentArray = array();
                $baseCommentArray['goods_id']       = $orderGoodsInfo->goods_id;
                $baseCommentArray['comment_writer'] = $commentArray['comment_writer'];
                $baseCommentArray['comment_time']   = $commentArray['comment_time'];
                $baseCommentArray['comment_count']  = $commentCount;
                $baseCommentInfo  = $this->getDbshopTable('GoodsCommentBaseTable')->InfoGoodsCommentBase(array('goods_id'=>$orderGoodsInfo->goods_id));

                if($baseCommentInfo) {
                    $this->getDbshopTable('GoodsCommentBaseTable')->updataGoodsCommentBase($baseCommentArray, array('goods_id'=>$orderGoodsInfo->goods_id));
                } else {
                    $this->getDbshopTable('GoodsCommentBaseTable')->addGoodsCommentBase($baseCommentArray);
                }
                //更新订单商品评价状态
                $this->getDbshopTable('OrderGoodsTable')->updateOrderGoods(array('comment_state'=>1), array('order_goods_id'=>$orderGoodsId, 'buyer_id'=>$userId));
                //更新订单表中的序列化商品评价状态
                $orderGoodsSerArray = unserialize($orderInfo->goods_serialize);
                $orderGoodsSerArray[$orderGoodsId]['comment_state'] = 1;
                $this->getDbshopTable('OrderTable')->updateOrder(array('goods_serialize'=>serialize($orderGoodsSerArray)), array('order_id'=>$orderGoodsInfo->order_id));

                return $this->createJson('success', $this->getDbshopLang()->translate('商品评价添加完成！'));
            }
        }

        return $this->createJson('error', $this->getDbshopLang()->translate('添加商品评论失败！'));
    }
    /**
     * 微信小程序充值支付
     * post
     * user_token   必填，用户登录唯一标识
     * code         必填，微信用户的code
     * money_num    必填，充值金额
     * paycheck_id  选填，当继续支付时，使用
     */
    public function moneyWxPayAction()
    {
        $userId     = isset($this->userData['user_id'])     ? intval($this->userData['user_id'])        : 0;//用户id
        $userName   = isset($this->userData['user_name'])   ? trim($this->userData['user_name'])          : '';//用户名称
        $moneyNum = isset($this->postData['money_num']) ? floatval($this->postData['money_num'])          : 0;//充值金额
        $code    = isset($this->postData['code'])       ? trim($this->postData['code'])       : '';
        $paycheckId = isset($this->postData['paycheck_id']) ? intval($this->postData['paycheck_id'])    : 0;//充值信息id

        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('调用充值信息失败！');
        $data   = array();

        //判断充值功能是否已经关闭，如果关闭无法进行充值
        $yezfInfo = $this->getServiceLocator()->get('frontHelper')->websitePaymentInfo('yezf');
        if((isset($yezfInfo['paycheck_state']['checked']) and $yezfInfo['paycheck_state']['checked'] != 1) or !isset($yezfInfo['paycheck_state']['checked'])) {
            return $this->createJson($status, $this->getDbshopLang()->translate('充值功能已经关闭！'));
        }
        $httpHost = $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost();
        $httpType = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps();

        if($userId > 0 and $moneyNum > 0 and !empty($code)) {
            $payArray = array();
            $payArray['money_change_num'] = $moneyNum;
            $payArray['pay_code']         = 'wxmpay';
            $payArray['pay_name']         = $this->getDbshopLang()->translate('微信小程序充值');
            $payArray['user_id']          = $userId;
            $payArray['user_name']        = $userName;
            $payArray['currency_code']    = 'CNY';
            $payArray['pay_state']        = 10;//未充值
            $payArray['paycheck_info']    = $this->getDbshopLang()->translate('微信小程序进行充值处理');
            $state = $this->getDbshopTable('PayCheckTable')->addPayCheck($payArray);
            if($state) {
                //打包数据，传给下面的支付输出
                $paymentData = array(
                    'app_id'    => apiConfig::WX_APP_ID,
                    'secret'    => apiConfig::WX_APP_SECRET,
                    'code'      => $code,
                    'moeny_num' => $moneyNum,
                    'shop_name' => $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name'),
                    'order_name'=> $this->getDbshopLang()->translate('会员充值'),
                    'goods_name'=> $this->getDbshopLang()->translate('微信小程序充值，充值会员：').$userName,
                    'notify_url'=> $httpType . $httpHost . $this->url()->fromRoute('frontmoney/default/paycheck_id', array('action'=>'paycheckNotifyPay', 'paycheck_id'=>$state)),
                );
                $data = $this->getServiceLocator()->get('wxmpay')->wxPayToMoney($paymentData);
                if($data['state']) {
                    $status = 'success';
                    $msg    = '支付调用成功！';
                    $data   = $data['jsPara'];
                } else $msg = $data['msg'];
            }
            return $this->createJsonData($data, $status, $msg);
        }
        return $this->createJson($status, $msg);
    }
    /**
     * 微信小程序通知发送
     * post
     * user_token   必填，用户登录唯一标识
     * order_id     必填，订单id
     * code         必填，获取openid的code
     * form_id      必填，表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id
     * state        必填，根据状态发送通知，这个状态值要与订单里面的匹配
     */
    public function wxSendMessageAction()
    {
        $userId  = isset($this->userData['user_id'])    ? intval($this->userData['user_id'])    : 0;//用户id
        $orderId = isset($this->postData['order_id'])   ? intval($this->postData['order_id'])   : 0;//订单id
        $state   = isset($this->postData['state'])      ? intval($this->postData['state'])      : 0;//状态
        $code    = isset($this->postData['code'])       ? trim($this->postData['code'])         : '';
        $formId  = isset($this->postData['form_id'])    ? trim($this->postData['form_id'])      : '';

        $res = json_encode(array());

        if($userId > 0 && $orderId > 0 && !empty($code) && !empty($formId)) {
            $orderInfo  = $this->getDbshopTable('OrderTable')->infoOrder(array('order_id'=>$orderId));

            if($orderInfo && $orderInfo->order_state == $state) {
                $openId = $this->getWxOpenId(apiConfig::WX_APP_ID, $code, apiConfig::WX_APP_SECRET);
                if(!empty($openId)) {
                    $array  = array('touser'=>$openId, 'form_id'=>$formId);
                    $data   = array();
                    switch ($state) {
                        case 0:     //取消订单
                            $array['template_id'] = apiConfig::WX_CANCEL_ORDER_TEMPLATE_ID;
                            $data = array(
                                'keyword1' => array('value' => $orderInfo->order_sn),
                                'keyword2' => array('value' => '已取消'),
                                'keyword3' => array('value' => $orderInfo->order_amount),
                                'keyword4' => array('value' => '该订单被您取消')
                                );
                            break;
                        case 10:    //下单
                            $array['template_id'] = apiConfig::WX_ADD_ORDER_TEMPLATE_ID;
                            $data = array(
                                'keyword1' => array('value' => $orderInfo->order_amount),
                                'keyword2' => array('value' => $orderInfo->order_sn),
                                'keyword3' => array('value' => '等待支付'),
                                'keyword4' => array('value' => '订单提交成功，请您尽快完成付款操作')
                            );
                            break;
                        case 20:    //订单付款完成
                            $array['template_id'] = apiConfig::WX_PAY_ORDER_TEMPLATE_ID;
                            $data = array(
                                'keyword1' => array('value' => $orderInfo->order_sn),
                                'keyword2' => array('value' => '已付款'),
                                'keyword3' => array('value' => $orderInfo->order_amount),
                                'keyword4' => array('value' => $orderInfo->pay_name),
                                'keyword5' => array('value' => '付款完成，等待商家发货')
                            );
                            break;
                        case 60:    //订单确认收货完成
                            $array['template_id'] = apiConfig::WX_FINISH_ORDER_TEMPLATE_ID;
                            $data = array(
                                'keyword1' => array('value' => $orderInfo->order_sn),
                                'keyword2' => array('value' => '订单确认收货'),
                                'keyword3' => array('value' => $orderInfo->order_amount),
                                'keyword4' => array('value' => '您完成了订单收货的确认处理')
                            );
                            break;
                    }
                    $array['data'] = $data;
                    if(!empty($data)) {
                        $url        = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$this->getWxAccessToken(apiConfig::WX_APP_ID, apiConfig::WX_APP_SECRET);
                        $jsonStr    = json_encode($array);

                        $curl = curl_init();
                        curl_setopt($curl, CURLOPT_URL, $url);
                        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
                        curl_setopt($curl, CURLOPT_POST, 1);
                        curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonStr);
                        curl_setopt($curl, CURLOPT_HEADER, 0);
                        curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($jsonStr)));

                        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                        $res = curl_exec($curl);
                    }
                }
            }
        }
        return $this->createJsonData(json_decode($res));
    }
    /**
     * 微信小程序支付
     * post
     * user_token   必填，用户登录唯一标识
     * order_id     必填，订单id
     * code         必填，微信用户的code
     * @return JsonModel|DbJsonModel
     */
    public function orderWxPayAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('调用订单支付信息失败！');
        $data   = array();

        $userId  = isset($this->userData['user_id'])    ? intval($this->userData['user_id'])    : 0;//用户id
        $orderId = isset($this->postData['order_id'])   ? intval($this->postData['order_id'])   : 0;//订单id
        $code    = isset($this->postData['code'])       ? trim($this->postData['code'])       : '';

        if($userId > 0 and $orderId > 0 and !empty($code)) {
            //订单基本信息
            $orderInfo  = $this->getDbshopTable('OrderTable')->infoOrder(array('order_id'=>$orderId));
            //判断支付方式是否非空，或者是否与购买者相对应
            if($orderInfo->order_state <= 0 or $orderInfo->pay_code == '' or $orderInfo->order_state >= 20 or $orderInfo->buyer_id != $userId) {
                return $this->createJson($status, $this->getDbshopLang()->translate('调用信息不完整或者该订单已经被取消，不能进行支付！'));
            }

            $httpHost = $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost();
            $httpType = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps();

            //订单配送信息
            $deliveryAddress = $this->getDbshopTable('OrderDeliveryAddressTable')->infoDeliveryAddress(array('order_id'=>$orderId));
            //订单商品
            $orderGoods = $this->getDbshopTable('OrderGoodsTable')->listOrderGoods(array('order_id'=>$orderId));
            //打包数据，传给下面的支付输出
            $paymentData = array(
                'app_id'    => apiConfig::WX_APP_ID,
                'secret'    => apiConfig::WX_APP_SECRET,
                'code'      => $code,
                'shop_name' => $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name'),
                'order'     => $orderInfo,
                'address'   => $deliveryAddress,
                'goods'     => $orderGoods,
                'notify_url'=> $httpType . $httpHost . $this->url()->fromRoute('m_wx/default/wx_order_id', array('action'=>'notify', 'order_id'=>$orderId)),
            );

            $data = $this->getServiceLocator()->get('wxmpay')->wxPayTo($paymentData);
            if($data['state']) {
                $status = 'success';
                $data   = $data['jsPara'];
            } else $msg = $data['msg'];
        } else {
            $msg = $this->getDbshopLang()->translate('会员信息或订单信息不完整，无法获取订单支付信息！');
        }
        return $this->createJsonData($data, $status, $msg);
    }
    /**
     * app订单支付调用（目前只支持支付宝、微信支付）
     * post
     * user_token   必填，用户登录唯一标识
     * order_id     必填，订单id
     * @return JsonModel
     */
    public function orderAppPayAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('调用订单支付信息失败！');
        $code   = 194;

        $userId  = isset($this->userData['user_id'])    ? intval($this->userData['user_id'])    : 0;//用户id
        $orderId = isset($this->postData['order_id'])   ? intval($this->postData['order_id'])   : 0;//订单id

        if($userId > 0 and $orderId > 0) {
            //订单基本信息
            $orderInfo  = $this->getDbshopTable('OrderTable')->infoOrder(array('order_id'=>$orderId));
            //判断支付方式是否非空，或者是否与购买者相对应
            if($orderInfo->order_state <= 0 or $orderInfo->pay_code == '' or $orderInfo->order_state >= 20 or $orderInfo->buyer_id != $userId) {
                return $this->createJson($status, $this->getDbshopLang()->translate('调用信息不完整或者该订单已经被取消，不能进行支付！'));
            }
            //只支持 支付宝和手机微信支付
            if(in_array($orderInfo->pay_code, array('alipay', 'malipay', 'wxmpay'))) {
                $httpHost = $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost();
                $httpType = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps();
                $notifyUrl = $httpType . $httpHost . $this->url()->fromRoute('frontorder/default/order_id', array('action'=>'orderAppNotifyPay', 'order_id'=>$orderId));

                require DBSHOP_PATH . '/module/Extendapp/Dbapi/config/app/appPayConf.php';

                //支付宝
                if(in_array($orderInfo->pay_code, array('alipay', 'malipay'))) {
                    require DBSHOP_PATH . '/module/Extendapp/Dbapi/src/Dbapi/Pay/AliAppPay/AopSdk.php';
                    $aop = new \AopClient();
                    $aop->gatewayUrl    = "https://openapi.alipay.com/gateway.do";
                    $aop->appId         = APP_ID;
                    $aop->rsaPrivateKey = file_get_contents(PRIVATE_KEY); //'请填写开发者私钥去头去尾去回车，一行字符串';
                    $aop->format        = "json";
                    $aop->postCharset   = "UTF-8";//demo里写的是 charset 属性在方法中不存在
                    $aop->signType      = SIGN_TYPE;
                    $aop->alipayrsaPublicKey = file_get_contents(ALIPAY_PUBLIC_KEY);//'请填写支付宝公钥，一行字符串';

                    $subject      = urldecode('商品购买');
                    $total_amount = $orderInfo->order_amount;
                    $out_trade_no = $orderInfo->order_sn;
                    // 业务参数数组
                    $bizContent = array(
                        "body"              => $subject,
                        "subject"			=> $subject,
                        "out_trade_no"		=> $out_trade_no,
                        "timeout_express"	=> "30m",
                        "total_amount"		=> $total_amount,
                        "product_code"		=> "QUICK_MSECURITY_PAY"
                    );

                    if(version_compare(phpversion(), '5.4', '<') === true) {
                        $bizContent = json_encode($bizContent);
                    } else {
                        $bizContent = json_encode($bizContent, JSON_UNESCAPED_UNICODE);
                    }

                    $request = new \AlipayTradeAppPayRequest();
                    //异步通知回调地址
                    $request->setNotifyUrl($notifyUrl);

                    $request->setBizContent($bizContent);

                    $response = $aop->sdkExecute($request);
                    $array = array(
                        'order_id' => $orderId,
                        'pay_code' => $orderInfo->pay_code,
                        //'pay_info' => htmlspecialchars($response)
                        'pay_info' => $response
                    );

                    return $this->createJson('success', $array);
                }

                //微信支付
                if($orderInfo->pay_code == 'wxmpay') {
                    require DBSHOP_PATH . '/module/Extendapp/Dbapi/src/Dbapi/Pay/WxAppPay/lib/Autoload.class.php';
                    spl_autoload_register("Autoload::autoload");

                    $out_trade_no       = $outOrderSn = str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT).'OrderSn'.$orderInfo->order_sn;
                    $total_fee          = $orderInfo->order_amount * 100;
                    $spbill_create_ip   = $_SERVER['REMOTE_ADDR'];
                    $body               = urldecode('商品购买');

                    $data = array(
                        'body'				=>	$body,
                        'out_trade_no'		=>	$out_trade_no,
                        'total_fee'			=>	$total_fee,
                        'spbill_create_ip'	=>	$spbill_create_ip,
                    );
                    //实例化签名类
                    $encpt = \WeEncryption::getInstance();
                    //$url = WE_NOTIFY_URL;
                    //设置异步通知地址
                    $encpt->setNotifyUrl($notifyUrl);

                    //实例化传输类；
                    $curl = new \Curl();
                    //发送请求
                    $xml_data = $encpt->sendRequest($curl, $data);
                    //解析返回数据
                    $postObj = $encpt->xmlToObject($xml_data);
                    if ($postObj === false) {
                        return $this->createJson($status, $this->getDbshopLang()->translate('微信第一次通信，无返回相应！'));
                    }

                    if ($postObj->return_code == 'FAIL') {
                        return $this->createJson($status, $postObj->return_msg);
                    } else {
                        $resignData = array(
                            'appid'	    =>	$postObj->appid,
                            'partnerid'	=>	$postObj->mch_id,
                            'prepayid'	=>	$postObj->prepay_id,
                            'noncestr'	=>	$postObj->nonce_str,
                            'timestamp'	=>	time(),
                            'package'	=>	'Sign=WXPay'
                        );
                        $sign = $encpt->getClientPay($resignData);
                        $resignData['sign'] = $sign;

                        $array = array(
                            'order_id' => $orderId,
                            'pay_code' => $orderInfo->pay_code,
                            'pay_info' => $resignData
                        );
                        return $this->createJson('success', $array);
                    }
                }
            }
        } else {
            $msg = $this->getDbshopLang()->translate('会员信息或订单信息不完整，无法获取订单支付信息！');
        }

        return $this->createJson($status, $msg);
    }
    /**
     * 订单完成付款
     * post
     * user_token   必填，用户登录唯一标识
     * order_id     必填，订单id
     * trade_no     非必填，只有外面支付有trade_no（外部订单号）时，并且传递过来，才会使用
     * state_info   非必填，支付凭证，只有在支付方式是 线下支付 的时候，才会有此内容的提交
     * @return JsonModel
     */
    public function orderPayFinishAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('该订单付款失败！');

        $userId  = isset($this->userData['user_id'])    ? intval($this->userData['user_id'])    : 0;//用户id
        $orderId = isset($this->postData['order_id'])   ? intval($this->postData['order_id'])   : 0;//订单id

        $tradeNo = isset($this->postData['trade_no'])   ? trim($this->postData['trade_no'])     : '';//外部订单编号
        $stateInfo = isset($this->postData['state_info']) ? trim($this->postData['state_info'])   : '';//订单凭证信息（只有支付方式是线下支付时才会使用）
        if($userId > 0 and $orderId > 0) {
            //订单基本信息
            $orderInfo  = $this->getDbshopTable('OrderTable')->infoOrder(array('order_id'=>$orderId));
            if(!in_array($orderInfo->pay_code, array('xxzf', 'yezf'))) return $this->createJson($status, $msg);
            //判断支付方式是否非空，或者是否与购买者相对应
            if($orderInfo->pay_code == '' or $orderInfo->order_state >= 20 or $orderInfo->buyer_id != $userId) return $this->createJson($status, $msg);
            //当是线下付款时，如果不进行下面的判断处理，会出现问题
            if($orderInfo->pay_code == 'xxzf' and $userId == '') return $this->createJson($status, $msg);
            //当时支付方式为余额付款时，进行单独处理，支付状态，抛给orderInfo
            if($orderInfo->pay_code == 'yezf') {
                $orderInfo = $this->userMoneyPayOper($orderInfo);
                if($orderInfo->yezfPayState == 'currency_error') return $this->createJson($status, $this->getDbshopLang()->translate('不是相同种类的货币支付！'));
                if($orderInfo->yezfPayState == 'false') return $this->createJson($status, $this->getDbshopLang()->translate('余额不足！'));
            }

            $paymentFinishTime = time();
            //在线支付或者为线下支付时的支付证明内容,当为线下支付付款时，这里状态修改为付款中状态（15）
            $updateOrderArray = array('order_state'=>($orderInfo->pay_code == 'xxzf' ? 15 : 20), 'order_out_sn'=>(!empty($tradeNo) ? $tradeNo : ''), 'pay_time'=>$paymentFinishTime, 'pay_certification'=>(!empty($stateInfo) ? $stateInfo : ''));
            //只有在订单状态非付款完成和非付款中时，才进行此处理
            if($orderInfo->order_state != 20 and $orderInfo->order_state != 15) {
                $this->getDbshopTable('OrderTable')->updateOrder($updateOrderArray, array('order_id'=>$orderId));
                //保存订单历史
                $this->getDbshopTable('OrderLogTable')->addOrderLog(array('order_id'=>$orderId, 'order_state'=>$updateOrderArray['order_state'], 'state_info'=>((isset($array['state_info']) and !empty($array['state_info'])) ? $array['state_info'] : ($updateOrderArray['order_state'] == 15 ? $this->getDbshopLang()->translate('付款进行中') : $this->getDbshopLang()->translate('支付完成'))), 'log_time'=>$paymentFinishTime, 'log_user'=>$this->userData['user_name']));
                //如果是线下支付，提交支付凭证，执行到下面这句即可
                if($orderInfo->pay_code == 'xxzf') return $this->createJson('success', $this->getDbshopLang()->translate('支付凭证提交完成！'));
            }

            if($updateOrderArray['order_state'] == 20 and $orderInfo->order_state != 20) {//当付款状态为完成时，进行邮件发送，如果只是付款中，则不进行邮件发送

                /*----------------------提醒信息发送----------------------*/
                $sendArray['buyer_name']  = $orderInfo->buyer_name;
                $sendArray['order_sn']    = $orderInfo->order_sn;
                $sendArray['order_total'] = $orderInfo->order_amount;
                $sendArray['time']        = $paymentFinishTime;
                $sendArray['buyer_email'] = $orderInfo->buyer_email;
                $sendArray['order_state'] = 'payment_finish';
                $sendArray['time_type']   = 'paymenttime';
                $sendArray['subject']     = $this->getDbshopLang()->translate('订单付款完成');
                $this->changeStateSendMail($sendArray);
                /*----------------------提醒信息发送----------------------*/

                /*----------------------手机提醒信息发送----------------------*/
                $smsData = array(
                    'buyname'   => $sendArray['buyer_name'],
                    'ordersn'    => $sendArray['order_sn'],
                    'ordertotal'=> $sendArray['order_total'],
                    'time'    => $sendArray['time'],
                );
                try {
                    $this->getServiceLocator()->get('shop_send_sms')->toSendSms(
                        $smsData,
                        $this->userData['user_phone'],
                        'alidayu_payment_order_template_id',
                        $userId
                    );
                } catch(\Exception $e) {

                }
                /*----------------------手机提醒信息发送----------------------*/
                //事件驱动
                $this->getEventManager()->trigger('order.pay.front.post', $this, array('values'=>$orderId));

                $status = 'success';
                $msg    = $this->getDbshopLang()->translate('该订单付款完成！');
            }

        }
        return $this->createJson($status, $msg);
    }
    /**
     * 订单确认收货
     * post
     * user_token   必填，用户登录唯一标识
     * order_id     必填，订单id
     * @return JsonModel
     */
    public function orderReceiptAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('该订单确认收货失败！');

        $userId  = isset($this->userData['user_id'])    ? intval($this->userData['user_id'])    : 0;//用户id
        $orderId = isset($this->postData['order_id'])   ? intval($this->postData['order_id'])   : 0;//订单id
        if($userId > 0 and $orderId > 0) {
            $array['order_info'] = $this->getDbshopTable('OrderTable')->infoOrder(array('order_id'=>$orderId, 'buyer_id'=>$userId));
            if(!$array['order_info']) return $this->createJson($status, $this->getDbshopLang()->translate('该订单信息错误！'));

            if(!empty($array['order_info']->pay_time) and $array['order_info']->order_state == 40) {
                $finishTime = time();
                $this->getDbshopTable('OrderTable')->updateOrder(array('order_state'=>60, 'finish_time'=>$finishTime), array('order_id'=>$orderId));
                //事件驱动
                $this->getEventManager()->trigger('order.finish.front.post', $this, array('values'=>$orderId));
                //保存订单历史
                $this->getDbshopTable('OrderLogTable')->addOrderLog(array('order_id'=>$orderId, 'order_state'=>60, 'state_info'=>$this->getDbshopLang()->translate('确认收货'), 'log_time'=>$finishTime, 'log_user'=>$this->userData['user_name']));
                //积分获取
                if($array['order_info']->integral_num > 0 or $array['order_info']->integral_type_2_num > 0) {
                    $integralLogArray = array();
                    $integralLogArray['user_id']           = $array['order_info']->buyer_id;
                    $integralLogArray['user_name']         = $array['order_info']->buyer_name;
                    $integralLogArray['integral_log_info'] = $this->getDbshopLang()->translate('商品购物，订单号为：') . $array['order_info']->order_sn . '<br>';
                    $integralLogArray['integral_log_time'] = time();

                    if($array['order_info']->integral_num > 0) {//消费积分
                        $integralLogArray['integral_num_log']  = $array['order_info']->integral_num;
                        $integralLogArray['integral_log_info'] .= $array['order_info']->integral_rule_info;
                        if($this->getDbshopTable('IntegralLogTable')->addIntegralLog($integralLogArray)) {
                            //会员消费积分更新
                            $this->getDbshopTable('UserTable')->updateUserIntegralNum($integralLogArray, array('user_id'=>$array['order_info']->buyer_id));
                        }
                    }
                    if($array['order_info']->integral_type_2_num > 0) {//等级积分
                        $integralLogArray['integral_num_log']  = $array['order_info']->integral_type_2_num;
                        $integralLogArray['integral_log_info'] .= $array['order_info']->integral_type_2_num_rule_info;
                        $integralLogArray['integral_type_id'] = 2;
                        if($this->getDbshopTable('IntegralLogTable')->addIntegralLog($integralLogArray)) {
                            //会员等级积分更新
                            $this->getDbshopTable('UserTable')->updateUserIntegralNum($integralLogArray, array('user_id'=>$array['order_info']->buyer_id), 2);
                            //等级积分变更后，判断等级是否有变化
                            $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$array['order_info']->buyer_id));
                            $groupId = $this->getDbshopTable('UserGroupTable')->checkUserGroup(array('group_id'=>$userInfo->group_id, 'integral_num'=>$userInfo->integral_type_2_num));
                            if($groupId) {
                                $this->getDbshopTable('UserTable')->updateUser(array('group_id'=>$groupId), array('user_id'=>$userInfo->user_id));
                                $userGroup = $this->getDbshopTable('UserGroupExtendTable')->infoUserGroupExtend(array('group_id'=>$groupId,'language'=>$this->getDbshopLang()->getLocale()));

                                $user_serialize = array(
                                    'user_name'      => $userInfo->user_name,
                                    'user_id'        => $userInfo->user_id,
                                    'user_email'     => $userInfo->user_email,
                                    'user_phone'     => $userInfo->user_phone,
                                    'group_id'       => $groupId,
                                    'user_group_name'=> $userGroup->group_name,
                                    'user_avatar'    => (!empty($userInfo->user_avatar) ? $userInfo->user_avatar : $this->getServiceLocator()->get('frontHelper')->getUserIni('default_avatar'))
                                );
                                $userLoginInfo = array(
                                    'user_serialize'=> serialize($user_serialize)
                                );
                                //更新登录信息存储
                                $this->getDbshopTable('ApiUserLoginTable')->updateUserLogin($userLoginInfo, array('user_id'=>$userInfo->user_id));

                                /*----------------------提醒信息发送----------------------*/
                                //订单配送信息
                                $deliveryAddress = $this->getDbshopTable('OrderDeliveryAddressTable')->infoDeliveryAddress(array('order_id'=>$orderId));

                                $sendArray['buyer_name']  = $array['order_info']->buyer_name;
                                $sendArray['order_sn']    = $array['order_info']->order_sn;
                                $sendArray['order_total'] = $array['order_info']->order_amount;
                                $sendArray['express_name']  = $deliveryAddress->express_name;
                                $sendArray['express_number']= $deliveryAddress->express_number;
                                $sendArray['time']        = $finishTime;
                                $sendArray['buyer_email'] = $array['order_info']->buyer_email;
                                $sendArray['order_state'] = 'transaction_finish';
                                $sendArray['time_type']   = 'finishtime';
                                $sendArray['subject']     = $this->getDbshopLang()->translate('确认收货交易完成');
                                $this->changeStateSendMail($sendArray);
                                /*----------------------提醒信息发送----------------------*/

                                /*----------------------手机提醒信息发送----------------------*/
                                $smsData = array(
                                    'buyname'   => $sendArray['buyer_name'],
                                    'ordersn'    => $sendArray['order_sn'],
                                    'ordertotal' => $sendArray['order_total'],
                                    'expressname'=> $sendArray['express_name'],
                                    'expressnumber' => $sendArray['express_number'],
                                    'time'    => $sendArray['time'],
                                );
                                try {
                                    $this->getServiceLocator()->get('shop_send_sms')->toSendSms(
                                        $smsData,
                                        $this->userData['user_phone'],
                                        'alidayu_finish_order_template_id',
                                        $userId
                                    );
                                } catch(\Exception $e) {

                                }
                                /*----------------------手机提醒信息发送----------------------*/
                            }
                        }
                    }
                }
                //查找是否有对应的订单生效优惠券
                $couponArray = $this->getDbshopTable('UserCouponTable')->useUserCoupon(array('dbshop_user_coupon.user_id'=>$userId, 'dbshop_user_coupon.get_order_id'=>$orderId, 'dbshop_user_coupon.coupon_use_state'=>1));

                $status = 'success';
                $msg    = $this->getDbshopLang()->translate('该订单确认收货成功！');
                if(!empty($couponArray)) {//判断是否有优惠券生效
                    return $this->createJsonData($couponArray, $status, $msg);
                } else return $this->createJson($status, $msg);
            }
        }
        return $this->createJson($status, $msg);
    }
    /**
     * 获取支付信息
     * post
     * user_token   必填，用户登录唯一标识
     * payment_code 必填，支付方式的标识字符串
     * @return JsonModel
     */
    public function paymentInfoAction()
    {
        $status = 'error';
        $msg    = $this->getDbshopLang()->translate('获取支付信息失败！');

        $userId  = isset($this->userData['user_id'])        ? intval($this->userData['user_id'])        : 0;//用户id
        $code    = isset($this->postData['payment_code'])   ? trim($this->postData['payment_code'])   : '';//支付标识
        if($userId > 0 and !empty($code)) {
            $filePath      = DBSHOP_PATH . '/data/moduledata/Payment/'.$code.'.php';
            if(file_exists($filePath)) {
                $paymentInfo = include($filePath);
                $paymentInfo['payment_logo']['content'] = $this->createDbshopImageUrl($paymentInfo['payment_logo']['content'], false);
                return $this->createJsonData($paymentInfo);
            }
        }

        return $this->createJson($status, $msg);
    }


    /**
     * 获取分销设置描述信息
     * post
     * user_token   必填，用户登录标识
     * @return JsonModel|DbJsonModel
     */
    public function distributionInfoAction()
    {
        $userId = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id
        $type   = isset($this->userData['type']) ? trim($this->userData['type']) : 'default';

        if($userId <= 0) return $this->createJson('error', $this->getDbshopLang()->translate('会员未登录！'));
        if(!in_array($type, array('default', 'pc', 'phone'))) $type = 'default';

        $array      = array('default' => 'distribution_info', 'pc' => 'distribution_info_pc', 'phone' => 'distribution_info_phone');
        $iniRead    = new Ini();
        $configPath = DBSHOP_PATH . '/module/Extendapp/Dbdistribution/data/config.ini';
        $info = '';
        if(file_exists($configPath)) {
            $config = $iniRead->fromFile($configPath);
            $info   = $config[$array[$type]];
        }

        return $this->createJsonData(array('info'=>$info));
    }
    /**
     * 获取会员的分销收入
     * post
     * user_token   必填，用户登录标识
     * @return JsonModel|DbJsonModel
     */
    public function distributionUserCostAction()
    {
        $userId = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id
        if($userId <= 0) return $this->createJson('error', $this->getDbshopLang()->translate('会员未登录！'));

        $fOneCost = $this->getDbshopTable('DistributionOrderTable')->distributionOrderCost(array('one_level_user_id'=>$userId, 'o_state'=>1));
        $nOneCost = $this->getDbshopTable('DistributionOrderTable')->distributionOrderCost(array('one_level_user_id'=>$userId, 'o_state'=>2));

        $fTopCost = $this->getDbshopTable('DistributionOrderTable')->distributionOrderCost(array('top_level_user_id'=>$userId, 'o_state'=>1), 'top');
        $nTopCost = $this->getDbshopTable('DistributionOrderTable')->distributionOrderCost(array('top_level_user_id'=>$userId, 'o_state'=>2), 'top');

        //f_cost 已到账，n_cost未到账
        return $this->createJsonData(array('f_cost'=>$fOneCost + $fTopCost, 'n_cost' => $nOneCost + $nTopCost));
    }
    /**
     * 分销用户列表
     * get
     * user_token   必填，用户登录标识
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * @return JsonModel|DbJsonModel
     */
    public function distributionUserListAction()
    {
        $userId  = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;

        if($userId <= 0) return $this->createJson('error', $this->getDbshopLang()->translate('该会员未登录！'));

        $array  = $this->pageAndQtyAndStart();
        $array['where'] = 'one_level_user_id='.$userId.' or top_level_user_id='.$userId;
        $array['user_id'] = $userId;
        $distributionUser = $this->getDbshopTable('DistributionUserTable')->apiDistributionUserList($array);
        if($distributionUser) {
            foreach ($distributionUser as $key => $value) {
                $value['f_cost'] = $value['f1_cost'] + $value['f2_cost'];
                $value['n_cost'] = $value['n1_cost'] + $value['n2_cost'];
                unset($value['f1_cost'], $value['f2_cost'], $value['n1_cost'], $value['n2_cost']);
                $distributionUser[$key] = $value;
            }
        }
        $userNum = $this->getDbshopTable('DistributionUserTable')->distributionUserTotal($array['where']);

        return $this->createJsonData(array('user_list'=>$distributionUser, 'user_num'=>$userNum));
    }

    /**
     * 提现申请
     * post
     * user_token   必填，用户登录标识
     * money_change_num 必填，提现金额
     * bank_name    必填，支付名称/开户银行/第三方支付名称
     * bank_account 必填，账户名称/开户名称
     * bank_card_number 必填，账号/卡号
     * @return JsonModel
     */
    public function addWithdrawAction()
    {
        $userId  = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id

        $changeMoney = isset($this->postData['money_change_num']) ? (float) $this->postData['money_change_num'] : 0;
        $bankName       = isset($this->postData['bank_name']) ? trim($this->postData['bank_name']) : '';
        $bankAccount    = isset($this->postData['bank_account']) ? trim($this->postData['bank_account']) : '';
        $bankCardNumber = isset($this->postData['bank_card_number']) ? trim($this->postData['bank_card_number']) : '';

        if($userId > 0 && $changeMoney > 0) {
            $withdrawInfo = $this->getDbshopTable('WithdrawLogTable')->infoWithdrawLog(array('user_id'=>$userId, 'withdraw_state'=>0));
            if($withdrawInfo) return $this->createJson('error', $this->getDbshopLang()->translate('已存在提现申请！'));

            $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$userId));
            if($userInfo->user_money < $changeMoney) return $this->createJson('error', $this->getDbshopLang()->translate('提现余额不足！'));

            $addWithdraw = array(
                'user_id'           => $userId,
                'user_name'         => $userInfo->user_name,
                'currency_code'     => $this->getServiceLocator()->get('frontHelper')->getFrontDefaultCurrency(),
                'money_change_num'  => $changeMoney,
                'bank_name'         => $bankName,
                'bank_account'      => $bankAccount,
                'bank_card_number'  => $bankCardNumber
            );
            $this->getDbshopTable('WithdrawLogTable')->addWithdrawLog($addWithdraw);

            return $this->createJson('success', $this->getDbshopLang()->translate('提现申请完成！'));
        }
        return $this->createJson('error', $this->getDbshopLang()->translate('申请失败！'));
    }

    /**
     * 提现记录列表
     * get
     * user_token   必填，用户登录唯一标识
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * @return DbJsonModel
     */
    public function listWithdrawAction()
    {
        $userId  = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id

        $withdrawList = array();
        if($userId) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'] = 'withdrawlog.user_id='.$userId;
            $withdrawList   = $this->getDbshopTable('WithdrawLogTable')->apiWithdrawLog($array);
            if(!empty($withdrawList)) {
                foreach ($withdrawList as $key => $value) {
                    if(!empty($value['withdraw_time'])) $value['withdraw_time'] = date("Y-m-d H:i:s", $value['withdraw_time']);
                    if(!empty($value['withdraw_finish_time'])) $value['withdraw_finish_time'] = date("Y-m-d H:i:s", $value['withdraw_finish_time']);

                    $withdrawList[$key] = $value;
                }
            }
        }
        return $this->createJsonData($withdrawList);
    }
    /**
     * 获取会员余额列表
     * get
     * user_token   必填，用户登录唯一标识
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * @return DbJsonModel
     */
    public function userMoneyAction()
    {
        $userId  = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;//用户id

        $moneyArray = array();
        if($userId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'] = 'moneylog.user_id='.$userId;
            $moneyArray = $this->getDbshopTable('UserMoneyLogTable')->apiUserMoneyLog($array);
            if(!empty($moneyArray)) {
                $typeArray = array(
                    1=>$this->getDbshopLang()->translate('充值'),
                    2=>$this->getDbshopLang()->translate('消费'),
                    3=>$this->getDbshopLang()->translate('提现'),
                    4=>$this->getDbshopLang()->translate('退款'),
                    5=>$this->getDbshopLang()->translate('分销提成'));
                foreach ($moneyArray as $key => $value) {
                    $value['money_change_time_text']    = date("Y-m-d H:i:s", $value['money_change_time']);
                    $value['money_pay_type_text']       = $typeArray[$value['money_pay_type']];
                    $moneyArray[$key] = $value;
                }
            }
        }
        return $this->createJsonData($moneyArray);
    }
    /**
     * 获取会员优惠券列表
     * get
     * user_token   必填，用户登录唯一标识
     * user_coupon_state 必填，如果不填写默认显示改会员全部优惠券，all 全部、0 未生效、1 已生效（可用）、2 已用、3 过期
     * page     必填，调取页数，如 第一页，第二页。如果不填写默认是 1
     * qty      必填，每页显示的商品数量，如果不填写默认是 10
     * @return DbJsonModel
     */
    public function userCouponListAction()
    {
        $stateArray = array('all', '0', '1', '2', '3', '4');

        $userId         = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;  //用户id
        $couponState    = (isset($this->getData['user_coupon_state']) and in_array($this->getData['user_coupon_state'], $stateArray))   ? trim($this->getData['user_coupon_state']) : 'all'; //会员优惠券状态
        $listUserCoupon = array();
        if($userId > 0) {
            $array  = $this->pageAndQtyAndStart();
            $array['where'] = 'user_coupon.user_id='.$userId;
            if($couponState != 'all') $array['where'] .= ' and user_coupon.coupon_use_state='.$couponState;

            $listUserCoupon = $this->getDbshopTable('ApiUserCouponTable')->listUserCouponPage($array);
            if(!empty($listUserCoupon)) {
                $couponStateArray = array(
                    0=>$this->getDbshopLang()->translate('未生效'),
                    1=>$this->getDbshopLang()->translate('已生效'),
                    2=>$this->getDbshopLang()->translate('已使用'),
                    3=>$this->getDbshopLang()->translate('已过期'));
                $typeArray = array(
                    'all_goods'     => $this->getDbshopLang()->translate('所有商品'),
                    'class_goods'   => $this->getDbshopLang()->translate('商品分类'),
                    'brand_goods'   => $this->getDbshopLang()->translate('商品品牌')
                );
                foreach($listUserCoupon as $key => $value) {
                    $couponGoodsBody = unserialize($value['coupon_goods_body']);
                    if($value['coupon_goods_type'] != 'all_goods' and !empty($couponGoodsBody)) {
                        $idStr = implode(',', $couponGoodsBody);
                        $nameArray  = array();
                        if($value['coupon_goods_type'] == 'class_goods') {
                            $classArray = $this->getDbshopTable('GoodsClassTable')->selectGoodsClass('class_id IN('.$idStr.')');
                            if(!empty($classArray)) {
                                foreach($classArray as $cValue) {
                                    $nameArray[] = $cValue['class_name'];
                                }
                            }
                        }
                        if($value['coupon_goods_type'] == 'brand_goods') {
                            $brandArray = $this->getDbshopTable('GoodsBrandTable')->listGoodsBrand(array('dbshop_goods_brand.brand_id IN ('.$idStr.')'));
                            if(!empty($brandArray)) {
                                foreach($brandArray as $bValue) {
                                    $nameArray[] = $bValue['brand_name'];
                                }
                            }
                        }
                        if($value['coupon_goods_type'] == 'GoodsTable') {
                            $goodsArray = $this->getDbshopTable('GoodsTable')->listGoods(array('dbshop_goods.goods_id IN ('.$idStr.')'));
                            if(!empty($goodsArray)) {
                                foreach($goodsArray as $gValue) {
                                    $nameArray[] = $gValue['goods_name'];
                                }
                            }
                        }

                        if(!empty($nameArray)) $value['coupon_goods_body'] = implode(',', $nameArray);
                    }
                    $value['coupon_goods_type']         = $typeArray[$value['coupon_goods_type']];
                    $value['coupon_state_text']         = $couponStateArray[$value['coupon_use_state']];
                    $value['coupon_expire_time_text']   = !empty($value['coupon_expire_time']) ? date("Y-m-d H:i:s", $value['coupon_expire_time']) : '';
                    $value['coupon_start_use_time_text']= !empty($value['coupon_start_use_time']) ? date("Y-m-d H:i:s", $value['coupon_start_use_time']) : '';

                    $userCouponState = true;
                    if($value['coupon_expire_time'] == '' and $value['coupon_start_use_time'] == '') {
                        $value['start_and_end_time'] = $this->getDbshopLang()->translate('长期有效');
                    } elseif($value['coupon_expire_time'] != '' and time() > $value['coupon_expire_time']) {
                        $userCouponState = false;
                        $value['start_and_end_time'] = $this->getDbshopLang()->translate('已经过期');
                    } else {
                        $value['start_and_end_time'] = (empty($value['coupon_start_use_time_text']) ? $this->getDbshopLang()->translate('无') : $value['coupon_start_use_time_text']) . ' ~ ' . (empty($value['coupon_expire_time_text']) ? $this->getDbshopLang()->translate('无') : $value['coupon_expire_time_text']);
                    }
                    $value['expire_state'] = $userCouponState ? (in_array($value['coupon_use_state'], array(0, 2, 3)) ? 1 : 0) : 1;
                    //使用渠道
                    //$value['coupon_use_channel'] = !empty($value['coupon_use_channel']) ? unserialize($value['coupon_use_channel']) : array();

                    $listUserCoupon[$key] = $value;
                }
            }
        }
        return $this->createJsonData($listUserCoupon);
    }
    /**
     * 获取会员优惠券统计信息
     * post
     * user_token   必填，用户登录唯一标识
     * @return JsonModel
     */
    public function userCouponNumAction()
    {
        $userId = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;  //用户id
        if($userId > 0) {
            $stateArray = $this->getDbshopTable('ApiUserCouponTable')->allStateNumCoupon(array('user_id'=>$userId));
            return $this->createJsonData($stateArray);
        }
        return $this->createJson('error');
    }

    /**
     * 获取微信小程序码
     * post
     * user_token   必填，用户登录唯一标识
     * @return JsonModel|DbJsonModel
     */
    public function weixinSmallQrcodeAction()
    {
        $userId = isset($this->userData['user_id']) ? intval($this->userData['user_id']) : 0;  //用户id
        if($userId > 0) {
            $accessToken= $this->getWxAccessToken(apiConfig::WX_APP_ID, apiConfig::WX_APP_SECRET);
            $url        = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$accessToken;
            $jsonStr    = json_encode(array('width'=> '800px', 'scene' => $userId));

            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonStr);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($jsonStr)));

            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $res = curl_exec($curl);

            $base64Image = 'data:image/png;base64,' . base64_encode($res);
            $savePath    = DBSHOP_PATH . '/public/upload/user/weixinInvitation';
            $image       = $this->base64ImageContent($base64Image, $savePath, $userId);
            $image       = $this->createDbshopImageUrl('/public/upload/user/weixinInvitation'.$image, false);
            return $this->createJsonData(array('image'=>$image));
        }
        return $this->createJson('error');
    }
    /*============================================用户中心相关============================================*/
    /**
     * 通用分页获取页数和开始值
     * @return array
     */
    private function pageAndQtyAndStart()
    {
        $page   = isset($this->getData['page']) ? ($this->getData['page']   > 0 ? intval($this->getData['page'])    : 1)    : 1;
        $qty    = isset($this->getData['qty'])  ? ($this->getData['qty']    > 0 ? intval($this->getData['qty'])     : 10)   : 10;
        $start  = $page > 1 ? (($page-1) * $qty) : 0;

        return array(
            'limit'     => (int) $qty,
            'offset'    => (int) $start
        );
    }
    /**
     * 生成json数据
     * @param $data
     * @param string $status
     * @param string $message
     * @return DbJsonModel
     */
    private function createJsonData($data, $status='success', $message='')
    {
        $msg    = $status == 'success' ? $this->getDbshopLang()->translate('信息调用成功！') : $this->getDbshopLang()->translate('信息调用失败！');
        if(!empty($message)) $msg = $message;
        $result = new DbJsonModel(array(
            'status'    => $status,
            'msg'       => $msg,
            'result'    => $data
        ));
        return $result;
    }
    /**
     * 抛出json信息
     * @param $status
     * @param $msg
     * @return JsonModel
     */
    private function createJson($status, $msg)
    {
        $result = new DbJsonModel(array(
            'status'    => $status,
            'msg'       => $msg
        ));
        return $result;
    }
    /**
     * 检查注册会员名称
     * @param $userName
     * @param string $userId
     * @return array
     */
    private function checkUserName($userName, $userId='')
    {
        //对是否用户名被限制检查
        $retainState    = true;
        $message        = '';

        $userName = trim($userName);
        if(empty($userName)) return array('status'=>false, 'msg'=>$this->getDbshopLang()->translate('注册名称不能为空！'));

        $registerRetain = $this->getServiceLocator()->get('frontHelper')->getUserIni('register_retain');
        if($registerRetain != '') {
            $registerRetain = explode('|', $registerRetain);
            if(in_array($userName, $registerRetain)) {
                $retainState = false;
                $message     = $this->getDbshopLang()->translate('很抱歉不能用该名称进行注册！');
            }
        }
        if($retainState){
            //检查是否存在
            $where['user_name'] = $userName;
            if(!empty($userId) and $userId > 0) $where[] = 'user_id!='.$userId;

            $userInfo = $this->getDbshopTable('UserTable')->infoUser($where);
            if(!empty($userInfo) and $userInfo->user_id != 0) {
                $retainState = false;
                $message     = $this->getDbshopLang()->translate('该名称已经存在，请更换名称进行注册！');
            }
        }

        return array('status'=>$retainState, 'message'=>$message);
    }
    /**
     * 检查用户邮箱
     * @param $userEmail
     * @param string $userId
     * @return array
     */
    private function checkUserEmail($userEmail, $userId='')
    {
        $retainState    = true;
        $message        = '';

        $where = array(
            'user_email'=>$userEmail
        );
        if(!empty($userId)) {
            $where[] = 'user_id!='.$userId;
        }

        $userInfo = $this->getDbshopTable('UserTable')->infoUser($where);
        if(!empty($userInfo) and $userInfo->user_id != 0) {
            $retainState = false;
            $message     = $this->getDbshopLang()->translate('该邮箱地址已经存在，请更换邮箱进行注册！');
        }
        return array('status'=>$retainState, 'message'=>$message);
    }
    /**
     * 检查用户手机号码
     * @param $userPhone
     * @param string $userId
     * @return array
     */
    private function checkUserPhone($userPhone, $userId='')
    {
        $retainState    = true;
        $message        = '';
        $phoneState = $this->getServiceLocator()->get('frontHelper')->checkPhoneNum($userPhone);//preg_match('#^13[\d]{9}$|^14[\d]{9}$|^15[\d]{9}$|^17[\d]{9}$|^18[\d]{9}$#', $userPhone) ? 'true' : 'false';
        if($phoneState == 'false') {
            $retainState = false;
            $message     = $this->getDbshopLang()->translate('不是正确的手机号码!');
        } else {
            $where = array(
                'user_phone'=>$userPhone
            );
            if(!empty($userId)) {
                $where[] = 'user_id!='.$userId;
            }
            $userInfo = $this->getDbshopTable('UserTable')->infoUser($where);
            if(!empty($userInfo) and $userInfo->user_id != 0) {
                $retainState = false;
                $message     = $this->getDbshopLang()->translate('该手机号码已经存在，请更换手机号码进行注册！');
            }
        }

        return array('status'=>$retainState, 'message'=>$message);
    }
    /**
     * 检查购物车中的商品价格是否有所改变
     * @param $userUnionid
     */
    private function checkCartGoodsPrice($userUnionid)
    {
        $array = array();
        $cartGoodsList = $this->getDbshopTable('ApiCartTable')->cartGoods(array('user_unionid'=>$userUnionid));
        if(is_array($cartGoodsList) and !empty($cartGoodsList)) {
            $userGroupId = isset($this->userData['group_id']) ? $this->userData['group_id'] : 0;
            foreach($cartGoodsList as $goodsValue) {
                $colorValue = $goodsValue['goods_color'];
                $sizeValue  = $goodsValue['goods_size'];
                $goodsId    = $goodsValue['goods_id'];
                $specTagId  = $goodsValue['goods_adv_tag_id'];

                //检查基础商品是否存在，并且状态是开启状态
                $goodsInfo = $this->getDbshopTable('GoodsTable')->infoGoods(array('dbshop_goods.goods_id'=>$goodsValue['goods_id'], 'dbshop_goods.goods_state'=>1));
                //不存在，进行购物车删除处理
                if(!$goodsInfo) {
                    $this->getDbshopTable('ApiCartTable')->delCart(array('goods_key'=>$goodsValue['goods_key'], 'user_unionid'=>$userUnionid));
                    continue;
                } else {//存在，则进行下一步处理
                    //判断优惠价格是否存在，是否过期
                    $preferentialStart = (intval($goodsInfo->goods_preferential_start_time) == 0 or time() >= $goodsInfo->goods_preferential_start_time) ? true : false;
                    $preferentialEnd   = (intval($goodsInfo->goods_preferential_end_time) == 0 or time() <= $goodsInfo->goods_preferential_end_time) ? true : false;
                    $goodsInfo->goods_preferential_price = ($preferentialStart and $preferentialEnd and $goodsInfo->goods_preferential_price > 0) ? $goodsInfo->goods_preferential_price : 0;

                    //当颜色和尺寸同时存在情况下，进行检查获取商品库存及颜色和尺寸值，赋值入基础商品中
                    if((isset($colorValue) and !empty($colorValue) and isset($sizeValue) and !empty($sizeValue)) or (isset($specTagId) and !empty($specTagId))) {
                        if($goodsInfo->goods_spec_type == 2) {
                            $extendGoods = $this->getDbshopTable('GoodsPriceExtendGoodsTable')->InfoPriceExtendGoods(array('adv_spec_tag_id'=>$specTagId, 'goods_id'=>$goodsId));
                            if(!$extendGoods) {//如何没有该属性的商品，则删除该商品在购物车中的存在
                                $this->getDbshopTable('ApiCartTable')->delCart(array('goods_key'=>$goodsValue['goods_key'], 'user_unionid'=>$userUnionid));
                                continue;
                            }
                            $goodsInfo->goods_stock      = $extendGoods->goods_extend_stock;
                            $goodsInfo->goods_item       = $extendGoods->goods_extend_item;
                            $goodsInfo->goods_shop_price = ($goodsInfo->goods_preferential_price <= 0 ? $extendGoods->goods_extend_price : $goodsInfo->goods_preferential_price);
                            $goodsInfo->goods_adv_tag_id = $specTagId;
                            //当未开启优惠价，判断是否有会员价
                            if($goodsInfo->goods_preferential_price <= 0 and $userGroupId > 0) {
                                $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsInfo->goods_id, 'user_group_id'=>$userGroupId, 'adv_spec_tag_id'=>$specTagId));
                                if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $goodsInfo->goods_shop_price = $userGroupPrice->goods_user_group_price;
                            }

                        } else {
                            $extendGoods = $this->getDbshopTable('GoodsPriceExtendGoodsTable')->InfoPriceExtendGoods(array('goods_color'=>$colorValue, 'goods_size'=>$sizeValue, 'goods_id'=>$goodsId));
                            if(!$extendGoods) {//如何没有该属性的商品，则删除该商品在购物车中的存在
                                $this->getDbshopTable('ApiCartTable')->delCart(array('goods_key'=>$goodsValue['goods_key'], 'user_unionid'=>$userUnionid));
                                continue;
                            }
                            $goodsInfo->goods_stock      = $extendGoods->goods_extend_stock;
                            $goodsInfo->goods_item       = $extendGoods->goods_extend_item;
                            $goodsInfo->goods_shop_price = ($goodsInfo->goods_preferential_price <= 0 ? $extendGoods->goods_extend_price : $goodsInfo->goods_preferential_price);
                            $goodsInfo->goods_color      = $extendGoods->goods_color;
                            $goodsInfo->goods_size       = $extendGoods->goods_size;

                            //当未开启优惠价，判断是否有会员价
                            if($goodsInfo->goods_preferential_price <= 0 and $userGroupId > 0) {
                                $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsInfo->goods_id, 'user_group_id'=>$userGroupId, 'goods_color'=>$colorValue, 'goods_size'=>$sizeValue));
                                if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $goodsInfo->goods_shop_price = $userGroupPrice->goods_user_group_price;
                            }
                        }

                    } else {//当颜色或者尺寸存在其中一情况下，将其中值赋值入基础商品中
                        //判断是否有优惠价格存在
                        $goodsInfo->goods_shop_price = ($goodsInfo->goods_preferential_price <= 0 ? $goodsInfo->goods_shop_price : $goodsInfo->goods_preferential_price);
                        //当未开启优惠价，判断是否有会员价
                        if($goodsInfo->goods_preferential_price <= 0 and $userGroupId > 0) {
                            $userGroupPrice = $this->getDbshopTable('GoodsUsergroupPriceTable')->infoGoodsUsergroupPrice(array('goods_id'=>$goodsInfo->goods_id, 'user_group_id'=>$userGroupId, 'goods_color'=>'', 'goods_size'=>'', 'adv_spec_tag_id'=>''));
                            if(isset($userGroupPrice->goods_user_group_price) and $userGroupPrice->goods_user_group_price > 0) $goodsInfo->goods_shop_price = $userGroupPrice->goods_user_group_price;
                        }
                    }
                }
                //当价格有所改变时，及时修改购物车中的商品价格
                if($goodsInfo->goods_shop_price > 0 and $goodsInfo->goods_shop_price != $goodsValue['goods_shop_price']) {
                    $this->getDbshopTable('ApiCartTable')->editCart(array('goods_shop_price'=>$goodsInfo->goods_shop_price), array('goods_key'=>$goodsValue['goods_key'], 'user_unionid'=>$userUnionid));
                }
            }
        }
    }
    /**
     * 获取购物车信息
     * @param $cartGoodsInfo
     * @param int $buyNum
     * @param string $type
     * @return array
     */
    private function getCartData($cartGoodsInfo, $buyNum=0, $type='')
    {
        $cartCountPrice     = 0;
        $cartCountWeight    = 0;
        $cartIntegralNum    = 0;

        $array = array();

        if(isset($cartGoodsInfo['user_id']) and $cartGoodsInfo['user_id'] > 0) {
            $where[] = "user_unionid='".$cartGoodsInfo['user_unionid']."' or user_id=".$cartGoodsInfo['user_id'];
        } else {
            $where['user_unionid'] = $cartGoodsInfo['user_unionid'];
        }
        $cartGoodsList = $this->getDbshopTable('ApiCartTable')->cartGoods($where);
        if(is_array($cartGoodsList) and !empty($cartGoodsList)) {
            $cartGoodsArray = array();
            foreach($cartGoodsList as $key => $value) {
                $cartCountPrice = $cartCountPrice + $value['goods_shop_price'] * $value['buy_num'];
                $cartCountWeight= $cartCountWeight + $value['goods_weight'] * $value['buy_num'];
                $cartIntegralNum= $cartIntegralNum + $value['integral_num'] * $value['buy_num'];

                $cartGoodsList[$key]['goods_shop_price'] = $this->getServiceLocator()->get('frontHelper')->shopPrice($value['goods_shop_price']);
                $cartGoodsList[$key]['class_id_array']   = unserialize($value['class_id_array']);
                if(!empty($value['goods_adv_tag_name'])) {
                    $cartGoodsList[$key]['goods_adv_tag_list'] = explode('<br>', str_replace(array('<strong>', '</strong>'), array(''), $value['goods_adv_tag_name']));
                }

                $cartGoodsArray[$value['goods_key']] = $value;
                $cartGoodsArray[$value['goods_key']]['class_id_array'] = $cartGoodsList[$key]['class_id_array'];//对serialize的array化
            }

            $array['cart_price']        = $this->getServiceLocator()->get('frontHelper')->shopPrice($cartCountPrice);
            $array['cart_weight']       = $cartCountWeight;
            $array['cart_integral_num'] = $cartIntegralNum;

            if($type == 'update') {//更新购物车时，输出的信息
                $array['update_goods']  = array(
                    'goods_key'         => $cartGoodsInfo['goods_key'],
                    'buy_goods_num'     => $buyNum,
                    'goods_count_price' => $cartGoodsInfo['goods_shop_price'] * $buyNum
                );
                $array['update_goods']['goods_count_price'] = $this->getServiceLocator()->get('frontHelper')->shopPrice($array['update_goods']['goods_count_price']);
            } else {//获取购物车时，输出的信息
                $array['cart_goods']    = $cartGoodsList;
            }

            $userGroupId = isset($this->userData['group_id']) ? $this->userData['group_id'] : '';
            $promtions   = $this->getServiceLocator()->get('frontHelper')->promotionsOrIntegralFun(array('cart_array'=>$cartGoodsArray), array('group_id'=>$userGroupId));
            $array['discount']  = array(//优惠
                'discount_name' => $promtions['promotionsCost']['discountName'],        //优惠名称
                'discount_cost' => $this->getServiceLocator()->get('frontHelper')->shopPrice($promtions['promotionsCost']['discountCost']),        //优惠金额
            );
            $array['integral']  = array(
                'integral_info'     => $promtions['integralInfo']['integalRuleInfo'],   //消费积分描述
                'integral_num'      => $promtions['integralInfo']['integralNum']        //消费积分数
            );
            $array['integral_1']= array(
                'integral_info'     => $promtions['integralInfo1']['integalRuleInfo'],  //等级积分描述
                'integral_num'      => $promtions['integralInfo1']['integralNum']       //等级积分数
            );
        }
        return $array;
    }
    /**
     * 检查购物车商品数量修改
     * @param $cartGoods
     * @param $value
     * @return string
     */
    private function editCartGoodsNumCheck($cartGoods, $value)
    {
        $msg = '';
        $goodsInfo = $this->getDbshopTable('GoodsTable')->oneGoodsInfo(array('goods_id'=>$cartGoods->goods_id, 'goods_state'=>1));
        //判断是否有最少购买数量限制
        if(isset($goodsInfo->goods_cart_buy_min_num) and $goodsInfo->goods_cart_buy_min_num > 0 and $goodsInfo->goods_cart_buy_min_num > $value)  $msg = sprintf($this->getDbshopLang()->translate('该商品最少需要购买%s个'),$goodsInfo->goods_cart_buy_min_num);
        //判断是否有最多购买数量限制
        if(isset($goodsInfo->goods_cart_buy_max_num) and $goodsInfo->goods_cart_buy_max_num > 0 and $goodsInfo->goods_cart_buy_max_num < $value) $msg = sprintf($this->getDbshopLang()->translate('该商品最多购买%s个'),$goodsInfo->goods_cart_buy_max_num);
        //如果没有限制最高数量，默认是50
        if($goodsInfo->goods_cart_buy_max_num == 0 and $value > 50 and $goodsInfo->goods_cart_buy_min_num == 0) $msg = sprintf($this->getDbshopLang()->translate('该商品最多购买%s个'),50);
        //检查是否和购物车限制相同，如果不同进行修改
        $where['goods_key'] = $cartGoods->goods_key;
        if(!empty($cartGoods->user_unionid)) $where['user_unionid'] = $cartGoods->user_unionid;
        elseif($cartGoods->user_id > 0) $where['user_id'] = $cartGoods->user_id;
        if(isset($goodsInfo->goods_cart_buy_min_num) and $goodsInfo->goods_cart_buy_min_num != $cartGoods->buy_min_num) {
            $this->getDbshopTable('ApiCartTable')->editCart(array('buy_min_num'=>$goodsInfo->goods_cart_buy_min_num), $where);
        }
        if(isset($goodsInfo->goods_cart_buy_max_num) and $goodsInfo->goods_cart_buy_max_num != $cartGoods->buy_max_num) {
            $this->getDbshopTable('ApiCartTable')->editCart(array('buy_max_num'=>$goodsInfo->goods_cart_buy_max_num), $where);
        }

        return $msg;
    }
    /**
     * 将商品内容里的图片替换为url访问的
     * @param $goodsBody
     * @return mixed
     */
    private function createDbshopGoodsBody($goodsBody)
    {
        if(defined('FRONT_CDN_STATE') and FRONT_CDN_STATE == 'true') {//开启cdn图片加速
            if(isset($GLOBALS['apiClient']) && $GLOBALS['apiClient'] == 'smallWeixin' && stripos(FRONT_CDN_HTTP_TYPE, 'http://') !== false) {
                $imageBaseUrl = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost();
            } else $imageBaseUrl = FRONT_CDN_HTTP_TYPE . FRONT_CDN_DOMAIN;
        } else {
            $imageBaseUrl = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost();
        }

        preg_match_all('/<img(.*)src="([^"]+)"[^>]+>/isU', $goodsBody, $matches);
        if(isset($matches[2]) and !empty($matches[2])) {
            $images         = $matches[2];
            $patterns       = array();
            $replacements   = array();
            foreach($images as $imageitem) {
                if(stripos($imageitem, 'http') === false) {
                    //$replacements[] = $imageBaseUrl . '/goods/'. basename($imageitem);
                    $replacements[] = $imageBaseUrl . $imageitem;
                    $patterns[]     = "/".preg_replace("/\//i","\/",$imageitem)."/";
                }
            }
            if(!empty($replacements)) {
                ksort($patterns);
                ksort($replacements);
                $goodsBody = preg_replace($patterns, $replacements, $goodsBody);
            }
        }

        return $goodsBody;
    }
    /**
     * 获取商品对应的属性数组
     * @param unknown $attributeGroupId
     * @param unknown $goodsId
     * @return multitype:string
     */
    private function getAttributeArray($attributeGroupId, $goodsId)
    {
        $attributeArray      = $this->getDbshopTable('GoodsAttributeTable')->listAttribute(array('dbshop_goods_attribute.attribute_group_id'=>$attributeGroupId, 'e.language'=>$this->getDbshopLang()->getLocale()));
        $attributeValueArray = $this->getDbshopTable('GoodsAttributeValueTable')->listAttributeValue(array('dbshop_goods_attribute_value.attribute_group_id'=>$attributeGroupId, 'e.language'=>$this->getDbshopLang()->getLocale()));
        $valueArray = array();
        if(is_array($attributeValueArray) and !empty($attributeValueArray)) {
            foreach ($attributeValueArray as $v_value) {
                $valueArray[$v_value['attribute_id']][$v_value['value_id']] = $v_value['value_name'];
            }
        }

        //获取已经插入商品中的属性值
        $goodsInAttribute = array();
        if($goodsId != '') {
            $goodsAttribute = $this->getDbshopTable('GoodsInAttributeTable')->listGoodsInAttribute(array('goods_id'=>$goodsId));
            if(is_array($goodsAttribute) and !empty($goodsAttribute)) {
                foreach ($goodsAttribute as $gA_value) {
                    $goodsInAttribute[$gA_value['attribute_id']] = $gA_value['attribute_body'];
                }
            }
        }

        $array = array();
        if(is_array($attributeArray) and !empty($attributeArray)) {
            foreach ($attributeArray as $a_value) {
                if(isset($goodsInAttribute[$a_value['attribute_id']]) and !empty($goodsInAttribute[$a_value['attribute_id']])) {
                    switch ($a_value['attribute_type']) {
                        case 'select'://下拉菜单
                        case 'radio'://单选菜单
                            $array[] = array(
                                'name'  => $a_value['attribute_name'],
                                'value' => $valueArray[$a_value['attribute_id']][$goodsInAttribute[$a_value['attribute_id']]]
                            );
                            break;
                        case 'checkbox'://复选菜单
                            $checkboxChecked = explode(',', $goodsInAttribute[$a_value['attribute_id']]);
                            $checkboxV       = '';
                            foreach ($checkboxChecked as $valueId) {
                                $checkboxV .= $valueArray[$a_value['attribute_id']][$valueId] . ' , ';
                            }
                            $array[] = array(
                                'name'  => $a_value['attribute_name'],
                                'value' => substr($checkboxV, 0, -2)
                            );
                            break;
                        case 'input'://输入表单
                        case 'textarea'://文本域表单
                        $array[] = array(
                            'name'  => $a_value['attribute_name'],
                            'value' => $goodsInAttribute[$a_value['attribute_id']]
                        );
                            break;
                    }
                }
            }
        }

        return $array;
    }
    /**
     * 订单商品保存
     * @param array $goodsArray
     * @param array $data
     */
    private function orderGoodsSave (array $goodsArray, array $data)
    {
        //判断库存是否正常，如不正常，停止该次操作返回 -1
        if(!$this->goodsStockOper($goodsArray)) {
            return -1;
        }
        //正常，继续往下处理
        $array = array();
        $array['order_id']          = $data['order_id'];
        $array['goods_id']          = $goodsArray['goods_id'];
        $array['class_id']          = $goodsArray['class_id'];
        $array['goods_item']        = $goodsArray['goods_item'];
        $array['goods_name']        = $goodsArray['goods_name'];
        $array['goods_extend_info'] = ($goodsArray['goods_color_name'] != '' ? '<p>' . $goodsArray['goods_color_name'] . '</p>' : '')
            . ($goodsArray['goods_size_name'] != '' ? '<p>' . $goodsArray['goods_size_name'] . '</p>' : '')
            . ($goodsArray['goods_adv_tag_name'] != '' ? $goodsArray['goods_adv_tag_name'] : '');
        $array['goods_color']       = $goodsArray['goods_color'];
        $array['goods_size']        = $goodsArray['goods_size'];
        $array['goods_spec_tag_id'] = $goodsArray['goods_adv_tag_id'];
        $array['goods_type']        = $goodsArray['goods_type'];
        //$array['goods_shop_price']  = $this->getServiceLocator()->get('frontHelper')->shopPrice($goodsArray['goods_shop_price']);
        $array['goods_shop_price']  = $goodsArray['goods_shop_price'];
        $array['buy_num']           = $goodsArray['buy_num'];
        $array['goods_image']       = $goodsArray['goods_image'];
        //$array['goods_amount']      = $this->getServiceLocator()->get('frontHelper')->shopPrice($goodsArray['goods_shop_price'] * $goodsArray['buy_num']);
        $array['goods_amount']      = $goodsArray['goods_shop_price'] * $goodsArray['buy_num'];
        $array['goods_count_weight']= $goodsArray['goods_weight'] * $goodsArray['buy_num'];
        $array['buyer_id']          = $this->userData['user_id'];

        return $this->getDbshopTable('OrderGoodsTable')->addOrderGoods($array);
    }

    /**
     * 库存操作处理
     * @param array $data
     * @return bool
     */
    private function goodsStockOper(array $data)
    {
        $where       = array();
        $whereExtend = array();
        $stockNum    = 0;
        $extendState = false;//是否有扩展商品信息，默认是无

        $where['goods_id'] = $data['goods_id'];
        $goodsInfo         = $this->getDbshopTable('GoodsTable')->oneGoodsInfo($where);
        //当后台管理开启库存状态显示时，直接返回即可，无需扣除库存
        if($goodsInfo->goods_stock_state_open == 1) return true;
        //否则得到当前商品库存
        $stockNum          = $goodsInfo->goods_stock;

        //判断是否有规格，如果有规格获取扩展表中的商品信息
        if($goodsInfo->goods_spec_type == 2) {
            if(isset($data['goods_adv_tag_id']) and !empty($data['goods_adv_tag_id'])) {
                $whereExtend['goods_id']        = $data['goods_id'];
                $whereExtend['adv_spec_tag_id'] = $data['goods_adv_tag_id'];
                $extendGoods                = $this->getDbshopTable('GoodsPriceExtendGoodsTable')->InfoPriceExtendGoods($whereExtend);
                if($extendGoods) {
                    $stockNum    = $extendGoods->goods_extend_stock;//默认库存
                    $extendState = true;//有扩展信息
                }
            }
        } else {
            if(isset($data['goods_color']) and !empty($data['goods_color']) and isset($data['goods_size']) and !empty($data['goods_size'])) {
                $whereExtend['goods_id']    = $data['goods_id'];
                $whereExtend['goods_color'] = $data['goods_color'];
                $whereExtend['goods_size']  = $data['goods_size'];
                $extendGoods                = $this->getDbshopTable('GoodsPriceExtendGoodsTable')->InfoPriceExtendGoods($whereExtend);
                if($extendGoods) {
                    $stockNum    = $extendGoods->goods_extend_stock;//默认库存
                    $extendState = true;//有扩展信息
                }
            }
        }

        //判断库存是否符合要求，并于购物数量进行比较
        if($stockNum > 0 and $data['buy_num'] > 0 and $stockNum >= $data['buy_num']) {
            $stockNum = $stockNum - $data['buy_num'];
            if($extendState) {
                $this->getDbshopTable('GoodsPriceExtendGoodsTable')->updatePriceExtendGoods(array('goods_extend_stock'=>$stockNum), $whereExtend);
            } else {
                $this->getDbshopTable('GoodsTable')->oneUpdateGoods(array('goods_stock'=>$stockNum), $where);
            }
            return true;
        }

        return false;
    }

    /**
     * 保存订单收货地址
     * @param $address
     * @param array $data
     */
    private function orderDeliveryAddressSave ($address, array $data)
    {
        $array = array();
        $array['order_id']      = $data['order_id'];
        $array['delivery_name'] = $address['true_name'];
        $array['region_id']     = $address['region_id'];
        $array['region_info']   = $address['region_value'];
        $array['region_address']= $address['address'];
        $array['zip_code']      = $address['zip_code'];
        $array['tel_phone']     = ($address['tel_area_code']=='' ? '' : $address['tel_area_code'] . '-') . $address['tel_phone'] . ($address['tel_ext']=='' ? '' : '-' . $address['tel_ext']);
        $array['mod_phone']     = $address['mod_phone'];
        $array['express_name']  = $data['express_name'];
        $array['express_time_info'] = $data['shipping_time'];
        $array['express_fee']   = $data['express_fee'];
        $array['express_id']    = $data['express_id'];

        $this->getDbshopTable('OrderDeliveryAddressTable')->addDeliveryAddress($array);
    }

    /**
     * 订单保存
     * @param array $orderArray
     * @return array
     */
    private function orderSave(array $orderArray)
    {
        $array = array();
        $array['order_id']            = '';
        $array['order_sn']            = $this->getServiceLocator()->get('frontHelper')->createOrderSn($this->userData['user_id']);
        $array['order_out_sn']        = '';//out' . $array['order_sn'];
        $array['goods_amount']        = (empty($orderArray['goods_total_price']) ? '0.00' : $orderArray['goods_total_price']);
        $array['order_amount']        = (empty($orderArray['order_total_price']) ? '0.00' : $orderArray['order_total_price']);
        $array['pay_fee']             = $orderArray['pay_price'];
        $array['express_fee']         = $orderArray['express_price'];
        $array['user_pre_fee']        = 0;//$orderArray['user_pre_price'];会员优惠费用，暂时没有用到，属于预留功能点
        $array['user_pre_info']       = '';//$orderArray[''];
        $array['buy_pre_fee']         = $orderArray['buy_pre_price'];
        $array['integral_buy_num']    = $orderArray['integral_buy_num'];
        $array['integral_buy_price']  = $orderArray['integral_buy_price'];
        $array['goods_weight_amount'] = $orderArray['goods_count_weight'];
        $array['order_state']         = $orderArray['order_state'];
        $array['pay_code']            = $orderArray['payment_code'];
        $array['pay_name']            = $orderArray['pay_name'];
        $array['express_id']          = $orderArray['express_id'];
        $array['buyer_id']            = $this->userData['user_id'];
        $array['buyer_name']          = $this->userData['user_name'];
        $array['buyer_email']         = $this->userData['user_email'];
        $array['express_name']        = $orderArray['express_name'];
        $array['order_time']          = time();
        $array['currency']            = $this->getServiceLocator()->get('frontHelper')->shopCurrency();
        $array['currency_symbol']     = $this->getServiceLocator()->get('frontHelper')->shopPriceSymbol();
        $array['currency_unit']       = $this->getServiceLocator()->get('frontHelper')->shopPriceUnit();
        $array['order_message']       = $orderArray['order_message'];
        $array['integral_num']        = $orderArray['integral_num'];
        $array['integral_rule_info']  = $orderArray['integral_rule_info'];
        $array['integral_type_2_num']            = $orderArray['integral_type_2_num'];
        $array['integral_type_2_num_rule_info']  = $orderArray['integral_type_2_num_rule_info'];
        //发票内容
        if($this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_invoice') == 'true') {
            if($orderArray['invoice_content'] != '' or $orderArray['invoice_title']) {
                $array['invoice_content'] = $orderArray['navigation_type'] . ' - ';
                if(!empty($orderArray['invoice_title'])) $array['invoice_content'] .= $this->getDbshopLang()->translate('发票抬头').'：' . $orderArray['invoice_title'] . ' - ';
                if(!empty($orderArray['invoice_content'])) $array['invoice_content'] .= $this->getDbshopLang()->translate('发票内容').'：' . $orderArray['invoice_content'];
            }
        }

        $orderId = $this->getDbshopTable('OrderTable')->addOrder($array);

        return array('order_id'=>$orderId, 'order_sn'=>$array['order_sn'], 'order_time'=>$array['order_time']);
    }

    /**
     * 余额支付，进行付款
     * @param $orderInfo
     */
    private function userMoneyPayOper($orderInfo)
    {
        $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_id'=>$this->userData['user_id']));
        //判断是否货币相同，如果不相同则进行错误提示
        if($orderInfo->currency != $this->getServiceLocator()->get('frontHelper')->getFrontDefaultCurrency())
        {
            $orderInfo->yezfPayState = 'currency_error';
            return $orderInfo;
        }
        //对账户余额进行当前货币汇率转换
        $userInfo->user_money = $this->getServiceLocator()->get('frontHelper')->shopPrice($userInfo->user_money);
        //判断用户是否有足够的余额进行付款
        if($userInfo->user_money < $orderInfo->order_amount) {
            $orderInfo->yezfPayState = 'false';
        } else {
            //开启数据库事务处理
            $this->getDbshopTable('dbshopTransaction')->DbshopTransactionBegin();

            $moneyChangedAmount = $userInfo->user_money - $orderInfo->order_amount;
            $moneyChangeNum     = '-'.$orderInfo->order_amount;
            $moneyLogArray      = array();
            $moneyLogArray['user_id']       = $userInfo->user_id;
            $moneyLogArray['user_name']       = $userInfo->user_name;
            $moneyLogArray['money_change_num']= $moneyChangeNum;
            $moneyLogArray['money_changed_amount'] = $moneyChangedAmount;
            $moneyLogArray['money_pay_state'] = 20;//20是已经处理（充值后者减值，10是待处理）
            $moneyLogArray['money_pay_type']  = 2;//支付类型，1充值，2消费，3提现，4退款
            $moneyLogArray['payment_code']    = 'yezf';
            $moneyLogArray['money_pay_info']  = $this->getDbshopLang()->translate('商品购买，订单编号为：').$orderInfo->order_sn;

            $state = $this->getDbshopTable('UserMoneyLogTable')->addUserMoneyLog($moneyLogArray);
            if($state) {
                //对会员表中的余额总值进行更新
                $moneyUpdateState = false;
                if($moneyLogArray['money_changed_amount'] >= 0) {
                    $this->getDbshopTable('UserTable')->updateUser(array('user_money'=>$moneyLogArray['money_changed_amount']), array('user_id'=>$userInfo->user_id));
                    $moneyUpdateState = true;
                }

                if($moneyUpdateState) {
                    $this->getDbshopTable('dbshopTransaction')->DbshopTransactionCommit();//事务确认
                    $orderInfo->yezfPayState = 'true';
                } else {
                    $this->getDbshopTable('dbshopTransaction')->DbshopTransactionRollback();//事务回滚
                    $orderInfo->yezfPayState = 'false';
                }
            } else {
                $orderInfo->yezfPayState = 'false';
            }

        }

        return $orderInfo;
    }

    /**
     * 取消订单时的库存处理
     * @param unknown $orderId
     */
    private function returnGoodsStock ($orderId)
    {
        $goodsArray = $this->getDbshopTable('OrderGoodsTable')->listOrderGoods(array('order_id'=>$orderId));
        if(is_array($goodsArray) and !empty($goodsArray)) {
            foreach ($goodsArray as $goodsValue) {
                $goodsInfo = '';
                $goodsInfo = $this->getDbshopTable('GoodsTable')->oneGoodsInfo(array('goods_id'=>$goodsValue['goods_id']));
                if($goodsInfo->goods_stock_state_open != 1) {//如果没有启用库存状态显示
                    if((!empty($goodsValue['goods_color']) and !empty($goodsValue['goods_size'])) || !empty($goodsValue['goods_spec_tag_id'])) {
                        if(!empty($goodsValue['goods_spec_tag_id'])) $whereExtend = array('goods_id'=>$goodsValue['goods_id'], 'adv_spec_tag_id'=>$goodsValue['goods_spec_tag_id']);
                        else $whereExtend = array('goods_id'=>$goodsValue['goods_id'], 'goods_color'=>$goodsValue['goods_color'], 'goods_size'=>$goodsValue['goods_size']);

                        $extendGoods = $this->getDbshopTable('GoodsPriceExtendGoodsTable')->InfoPriceExtendGoods($whereExtend);
                        $this->getDbshopTable('GoodsPriceExtendGoodsTable')->updatePriceExtendGoods(array('goods_extend_stock'=>($extendGoods->goods_extend_stock + $goodsValue['buy_num'])), $whereExtend);
                    } else {
                        $this->getDbshopTable('GoodsTable')->oneUpdateGoods(array('goods_stock'=>($goodsInfo->goods_stock + $goodsValue['buy_num'])), array('goods_id'=>$goodsValue['goods_id']));
                    }
                }
            }
        }
    }

    /**
     * 订单变更发送邮件
     * @param array $data
     */
    private function changeStateSendMail(array $data)
    {
        $sendMessageBody = $this->getServiceLocator()->get('frontHelper')->getSendMessageBody($data['order_state']);
        if($sendMessageBody != '') {
            $sendArray = array();
            $sendArray['shopname']      = $this->getServiceLocator()->get('frontHelper')->websiteInfo('shop_name');
            $sendArray['buyname']       = $data['buyer_name'];
            $sendArray['ordersn']       = $data['order_sn'];
            $sendArray['ordertotal']    = isset($data['order_total'])    ? $data['order_total'] : '';
            $sendArray['expressname']   = isset($data['express_name'])   ? $data['express_name'] : '';
            $sendArray['expressnumber'] = isset($data['express_number']) ? $data['express_number'] : '';
            $sendArray[$data['time_type']]= $data['time'];
            $sendArray['shopurl']       = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost() . $this->url()->fromRoute('shopfront/default');

            $sendArray['subject']       = $sendArray['shopname'] . $data['subject'];
            $sendArray['send_mail'][]   = $this->getServiceLocator()->get('frontHelper')->getSendMessageBuyerEmail($data['order_state'] . '_state', $data['buyer_email']);
            $sendArray['send_mail'][]   = $this->getServiceLocator()->get('frontHelper')->getSendMessageAdminEmail($data['order_state'] . '_state');

            $sendMessageBody            = $this->getServiceLocator()->get('frontHelper')->createSendMessageContent($sendArray, $sendMessageBody);
            try {
                $sendState = $this->getServiceLocator()->get('shop_send_mail')->SendMesssageMail($sendArray, $sendMessageBody);
                $sendState = ($sendState ? 1 : 2);
            } catch (\Exception $e) {
                $sendState = 2;
            }
            //记录给用户发的电邮
            if($sendArray['send_mail'][0] != '') {
                $userInfo = $this->getDbshopTable('UserTable')->infoUser(array('user_name'=>$sendArray['buyname']));
                $sendLog = array(
                    'mail_subject' => $sendArray['subject'],
                    'mail_body'    => $sendMessageBody,
                    'send_time'    => time(),
                    'user_id'      => $userInfo->user_id,
                    'send_state'   => $sendState
                );
                $this->getDbshopTable('UserMailLogTable')->addUserMailLog($sendLog);
            }
        }
    }

    /**
     * 微信或者小程序获取 access_token （expires_in 有效期，时间 秒）
     * @param $appId
     * @param $secret
     * @return mixed
     */
    private function getWxAccessToken($appId, $secret)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$secret;

        $data = json_decode(file_get_contents(DBSHOP_PATH . "/module/Extendapp/Dbapi/data/access_token.json"));
        $newTime = time();
        if($data->expires_time < $newTime) {
            //初始化curl
            $ch = curl_init();
            //设置超时
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            //运行curl，结果以jason形式返回
            $res = curl_exec($ch);
            curl_close($ch);
            //取出access_token
            $data = json_decode($res,true);
            $accessToken = $data['access_token'];
            if($accessToken) {
                $fp = fopen(DBSHOP_PATH . "/module/Extendapp/Dbapi/data/access_token.json", "w");
                fwrite($fp, json_encode(array('access_token'=>$accessToken, 'expires_time'=> $newTime + 7000)));
                fclose($fp);
            }
        } else {
            $accessToken = $data->access_token;
        }

        return $accessToken;
    }

    /**
     * 在上面的方法中使用，获取对应的会员组
     * @param $cValue
     * @param $userGroup
     * @return array
     */
    private function getUserGroup($cValue, $userGroup)
    {
        $userGroupArray = array();
        if($cValue['get_user_type'] == 'user_group') {
            $getUserGroup = unserialize($cValue['get_user_group']);
            if(!empty($getUserGroup)) {
                foreach ($userGroup as $value) {
                    if(in_array($value['group_id'], $getUserGroup)) $userGroupArray[$value['group_id']] = $value['group_name'];
                }
            }
        }
        return $userGroupArray;
    }

    /**
     * 微信小程序获取openid
     * @param $code
     * @param $secret
     * @return mixed
     */
    private function getWxOpenId($appId, $code, $secret)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appId.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //运行curl，结果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res,true);
        $openid = $data['openid'];
        return $openid;
    }
    private function filterEmoji($str) {
        $str = preg_replace_callback('/./u', function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        }, $str);
        return $str;
    }

    /**
     * 将base64图片转换为图片存在本地
     * @param $base64ImageContent
     * @param $path
     * @param $imageName
     * @return bool|string
     */
    function base64ImageContent($base64ImageContent, $path, $imageName)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64ImageContent, $result)) {
            $type = $result[2];
            $new_file = $path . "/";
            if (!file_exists($new_file)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            $new_file = $new_file . $imageName . ".{$type}";
            if(file_exists($new_file)) return '/'. $imageName . ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64ImageContent)))) {
                return '/'. $imageName . ".{$type}";
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /**
     * 数据表调用
     * @param string $tableName
     * @return multitype:
     */
    private function getDbshopTable ($tableName='ApiGoodsTable')
    {
        if (empty($this->dbTables[$tableName])) {
            $this->dbTables[$tableName] = $this->getServiceLocator()->get($tableName);
        }
        return $this->dbTables[$tableName];
    }

    /**
     * 语言包调用
     * @return array|object
     */
    private function getDbshopLang ()
    {
        if (! $this->translator) {
            $this->translator = $this->getServiceLocator()->get('translator');
        }
        return $this->translator;
    }
}